Android: Draw text to dynamically sized bitmap


/ Published in: Java
Save to your folder(s)

This method draws a specified string to a Bitmap with the desired text width and text size.


Copy this code and paste it in your HTML
  1. public static Bitmap drawText(String text, int textWidth, int textSize) {
  2. // Get text dimensions
  3. TextPaint textPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG
  4. | Paint.LINEAR_TEXT_FLAG);
  5. textPaint.setStyle(Paint.Style.FILL);
  6. textPaint.setColor(Color.BLACK);
  7. textPaint.setTextSize(textSize);
  8. StaticLayout mTextLayout = new StaticLayout(text, textPaint,
  9. textWidth, Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
  10.  
  11. // Create bitmap and canvas to draw to
  12. Bitmap b = Bitmap.createBitmap(textWidth, mTextLayout.getHeight(), Config.RGB_565);
  13. Canvas c = new Canvas(b);
  14.  
  15. // Draw background
  16. Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG
  17. | Paint.LINEAR_TEXT_FLAG);
  18. paint.setStyle(Paint.Style.FILL);
  19. paint.setColor(Color.WHITE);
  20. c.drawPaint(paint);
  21.  
  22. // Draw text
  23. c.save();
  24. c.translate(0, 0);
  25. mTextLayout.draw(c);
  26. c.restore();
  27.  
  28. return b;
  29. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.