TextView Drawing Principles in Android
Posted SamDlex
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 fromthe highest characterto 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.
以上是关于TextView Drawing Principles in Android的主要内容,如果未能解决你的问题,请参考以下文章
如何更改无法从 'System.Drawing.Image' 转换为 'System.Drawing.Image[]?
Mono 是不是支持 System.Drawing 和 System.Drawing.Printing? [关闭]
vs2017 在引用管理器 添加 system.drawing
使用 System.Drawing.Font.FromHfont(IntPtr hfont) 从 SYSTEM_FONT Stock 对象创建 System.Drawing.Font