Advertisement
dzikovskyy

Drawing text on bitmap, Android

May 26th, 2016
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.77 KB | None | 0 0
  1. public Bitmap drawMultilineTextOnBitmap(Context context, int resId, String text) {
  2.  
  3.         // prepare canvas
  4.         Resources resources = context.getResources();
  5.         float scale = resources.getDisplayMetrics().density;
  6.         Bitmap bitmap = BitmapFactory.decodeResource(resources, resId);
  7.  
  8.         android.graphics.Bitmap.Config bitmapConfig = bitmap.getConfig();
  9.         // set default bitmap config if none
  10.         if(bitmapConfig == null) {
  11.             bitmapConfig = android.graphics.Bitmap.Config.ARGB_8888;
  12.         }
  13.         // resource bitmaps are immutable, so we need to convert it to mutable one
  14.         bitmap = bitmap.copy(bitmapConfig, true);
  15.         Canvas canvas = new Canvas(bitmap);
  16.  
  17.         // new antialiased Paint
  18.         TextPaint paint=new TextPaint(Paint.ANTI_ALIAS_FLAG);
  19.         // text color - #3D3D3D
  20.         paint.setColor(Color.rgb(61, 61, 61));
  21.         // text size in pixels
  22.         paint.setTextSize((int) (14 * scale));
  23.         // text shadow
  24.         paint.setShadowLayer(1f, 0f, 1f, Color.WHITE);
  25.  
  26.         // set text width to canvas width minus 16dp padding
  27.         int textWidth = canvas.getWidth() - (int) (16 * scale);
  28.  
  29.         // init StaticLayout for text
  30.         StaticLayout textLayout = new StaticLayout(text, paint, textWidth, Layout.Alignment.ALIGN_CENTER, 1.0f, 0.0f, false);
  31.  
  32.         // get height of multiline text
  33.         int textHeight = textLayout.getHeight();
  34.  
  35.         // get position of text's top left corner
  36.         float x = (bitmap.getWidth() - textWidth)/2;
  37.         float y = (bitmap.getHeight() - textHeight)/2;
  38.  
  39.         // draw text to the Canvas center
  40.         canvas.save();
  41.         canvas.translate(x, y);
  42.         textLayout.draw(canvas);
  43.         canvas.restore();
  44.  
  45.         return bitmap;
  46.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement