TextView Drawing Principles in Android

网友投稿 687 2022-09-03

TextView Drawing Principles in Android

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 = 100fval centerY = 100fval mPaint = Paint()mPaint.isAntiAlias = truemPaint.textSize = 30mPaint.color = Color.BLACKvar baseline = centerY + (abs(mPaint.fontMetricsInt.ascent)-mPaint.fontMetricsInt.descent)/2canvas?.drawText("Hello world",centerX,baseline,mPaint)

The characters will be displayed as you expected! That’s it today! Thank you.

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:慌的一批!妹子一个rm -rf把公司服务器数据删没了...
下一篇:复习基础:MongoDB的十大总结(mongodb特点)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~