Android文字基线
1、设置画笔
[^code 1]:
private val mText = "ABCDefg"
mTextPain = Paint(Paint.ANTI_ALIAS_FLAG)
mTextPain.color = Color.BLACK
mTextPain.textSize = sp2px(50f)
2、获取文字的宽高
[^code 2]:
val bounds = Rect()
mTextPain.getTextBounds(mText, 0, mText!!.length, bounds)
widthSize = bounds.width()//文字的宽高
heightSize = bounds.height()
3、获取文字的Metrics
下面代码中的top和bottom的值是相对于基线(baseLine = 0)的距离
[^code 3]:
val metrics = mTextPain.fontMetrics
val top = metrics.top
val bottom = metrics.bottom
val ascent = metrics.ascent
val descent = metrics.descent
top = -138.62 , bottom = 35.568237, ascent = -121.76514, descent = 32.043457
4、基线到中线的距离
code 3中,在Y方向上以BaseLine作为基准坐标,由于绘制文字时Leading一般为0,不考虑Leading,可以得到
top、ascent 坐标为负,bottom、descent 坐标为正
基线到中线的距离 = (descent - ascent) / 2 - descent
val dy = (descent - ascent) / 2 - descent
5、确认基线坐标
在0~height,要使文字居中显示,应当使文字的中线坐标和区域的中线坐标一致。绘制区域的(0,0)为坐标原点,因此y方向上
中线坐标 = height / 2
在该区域内,由于文字的中线和区域的中线坐标是相等的,所以
基线坐标 = 中线坐标 + 基线到中线的距离(Android坐标y轴向下为正)
val baseLine = height.toFloat() / 2 + dy
我自己写了一个关于文字基线的小demo,如果还不太清楚可以参考下,运行后的效果如下
github地址