Android Setting up Paint for text


Text drawing settings

  • setTypeface(Typeface typeface) Set the font face. See Typeface
  • setTextSize(int size) Set the font size, in pixels.
  • setColor(int color) Set the paint drawing color, including the text color. You can also use setARGB(int a, int r, int g, int b and setAlpha(int alpha)
  • setLetterSpacing(float size) Set the spacing between characters, in ems. Default value is 0, a negative value will tighten the text, while a positive one will expand it.
  • setTextAlign(Paint.Align align) Set text alignment relative to its origin. Paint.Align.LEFT will draw it to the right of the origin, RIGHT will draw it to the left, and CENTER will draw it centered on the origin (horizontally)
  • setTextSkewX(float skewX) This could be considered as fake italic. SkewX represents the horizontal offset of the text bottom. (use -0.25 for italic)
  • setStyle(Paint.Style style) Fill text FILL, Stroke text STROKE, or both FILL_AND_STROKE

Note that you can use TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, size, getResources().getDisplayMetrics()) to convert from SP or DP to pixels.

Measuring text

  • float width = paint.measureText(String text) Measure the width of text
  • float height = paint.ascent() Measure the height of text
  • paint.getTextBounds(String text, int start, int end, Rect bounds Stores the text dimensions. You have allocate the Rect, it cannot be null:
 String text = "Hello world!";
 Rect bounds = new Rect();
 paint.getTextBounds(text, 0, text.length(), bounds);

There are other methods for measuring, however these three should fit most purposes.