Guest User

Untitled

a guest
Feb 26th, 2017
187
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.30 KB | None | 0 0
  1. // int gravity: see android.view.Gravity, like Gravity.LEFT, Gravity.BOTTOM, etc
  2. public Bitmap addText(Bitmap in, String text, int gravity){
  3. Bitmap out = in.copy(Bitmap.Config.ARGB_8888,true);
  4. Canvas canvas = new Canvas(out);
  5.  
  6. Paint paint = new Paint();
  7. paint.setColor(Color.WHITE);
  8. paint.setStyle(Paint.Style.FILL);
  9. Paint textPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
  10. textPaint.setColor(Color.BLACK);
  11. // textPaint.setTextSize(128);
  12. textPaint.setTextAlign(Paint.Align.LEFT);
  13.  
  14. Rect inBounds = new Rect();
  15. textPaint.getTextBounds(text, 0, text.length(), inBounds);
  16. float scale = out.getWidth() * 0.35f / inBounds.width();
  17.  
  18. Rect container = new Rect(0, 0, out.getWidth(), out.getHeight());
  19. Rect outBounds = new Rect();
  20. int w = (int) (inBounds.width() * scale);
  21. int h = (int) (inBounds.height() * scale);
  22. Gravity.apply(gravity, w, h, container, outBounds);
  23.  
  24. canvas.drawRect(outBounds, paint);
  25. Matrix matrix = new Matrix();
  26. RectF src = new RectF(inBounds);
  27. RectF dst = new RectF(outBounds);
  28. matrix.setRectToRect(src, dst, Matrix.ScaleToFit.CENTER);
  29. canvas.concat(matrix);
  30. canvas.drawText(text, 0, 0, textPaint);
  31. return out;
  32. }
Add Comment
Please, Sign In to add comment