TextView Drawing Principles in Android
Let’s start with an image:
Here is the question:the text drawn in your custom view is a little up,when drawText()
is called. That is what we want to talk about in this article.
When the text is drawn,the top,bottom,ascent,descent and baseline values will be confirmed according to the current front size.So you should setup textSize filed of Paint object first.These values can be obtained by mPaint.getFontMetricsInt()
.
- Baseline:the base point of a character in TextView. The drawing of a character is done through this baseline. The value of top,bottom,ascent,descent is obtained from this zero point.Top and ascent above baseline are negative,and bottom and descent below the baseline are positive.
- Top:it refers to the value from the highest character to the base,which is a negative number.
- Ascent:the distance from the top of the base line to the top of the character,i.e. the maximum ascent,which is also a negative number.
- Descent:The distance from the base line to the lowest point of the character,which is a positive number.
- Bottom:it refers to the value from the lowest character to the base ,i.e. the maximum descent,which is a positive number.
It is easy for you to determine the position of the characters,when you got all the info above.
How to draw a character in the center position? I get that most of the android developers have come across this problem ,when they try to custom their view.Here we go:
For Java:
float centerX = 100;
float centerY = 100;
Paint mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setTextSize(30);
mPaint.setColor(Color.BLACK);
// Note!!!
float baseline = centerY + (Math.abs(mPaint.getFontMetricsInt().ascent)-mPaint.getFontMetricsInt().descent)/2;
canvas.drawText("Hello world",centerX,baseline,mPaint);
For Kotlin:
val centerX = 100f
val centerY = 100f
val mPaint = Paint()
mPaint.isAntiAlias = true
mPaint.textSize = 30
mPaint.color = Color.BLACK
var baseline = centerY + (abs(mPaint.fontMetricsInt.ascent)-mPaint.fontMetricsInt.descent)/2
canvas?.drawText("Hello world",centerX,baseline,mPaint)
The characters will be displayed as you expected!
That’s it today! Thank you.
上一篇: Kotlin初探