What is the difference between Paint and TextPaint in Android?
TextPaint
is a subclass of Paint
. However, contrary to what you might guess from these names, the heavy work of drawing the text on the canvas is done by Paint
. Thus, this
TextPaint textPaint = new TextPaint();
textPaint.setTextSize(50);
canvas.drawText("some text", 10, 100, textPaint);
and this
Paint paint = new Paint();
paint.setTextSize(50);
canvas.drawText("some text", 10, 100, paint);
actually do the same thing. TextPaint
is just a light wrapper around Paint
and gives Android some extra data to work with when drawing and measuring text. You can see this in action if you read the TextLine
class source code (this class draws a line of text). This is apparently why you have to pass in a TextPaint
and not a Paint
object when creating something like a StaticLayout
.
TextPaint fields
The documentation is pretty sparse on what the "extra data" is here is a little fuller explanation. (Disclamer: By changing these values in a TextPaint
, I couldn't actually affect any changes to how the text was drawn in my tests. So take this section with a grain of salt.)
baselineShift
- The baseline is the line at the base of the text. See this answer for an image. ChangingbaselineShift
causes the baseline to move up or down so it affects how high the text is drawn on a line.bgColor
- This is the background color behind the text.density
- I assume this is the screen density but I couldn't find it being used in any source code.drawableState
- I couldn't find much in the source code except aPFLAG_DRAWABLE_STATE_DIRTY
flag, which makes me think this is used to let objects know when they need to be redrawn.linkColor
- I can only assume this means what it says, the text color of a link. However, I couldn't find this being used in any source code.
Notes
TextPaint
source codePaint
source code- Please leave a note or update this answer if you have any more information.