Setting up Paint for text
suggest changeText drawing settings
setTypeface(Typeface typeface)Set the font face. See TypefacesetTextSize(int size)Set the font size, in pixels.setColor(int color)Set the paint drawing color, including the text color. You can also usesetARGB(int a, int r, int g, int bandsetAlpha(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.LEFTwill draw it to the right of the origin,RIGHTwill draw it to the left, andCENTERwill 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 textFILL, Stroke textSTROKE, or bothFILL_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 textfloat height = paint.ascent()Measure the height of textpaint.getTextBounds(String text, int start, int end, Rect boundsStores 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.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents