获取文字的相关属性:
1.Paint.FontMetrics()
用法
private val paint = Paint().apply {
isAntiAlias = true
textSize = 120.dp
style = Paint.Style.FILL
}
private val fontMetrics = Paint.FontMetrics()
@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
paint.getFontMetrics(fontMetrics)
canvas.drawText("qwer", 0f, -fontMetrics.ascent, paint)
println("descent ${fontMetrics.descent} ascent ${fontMetrics.ascent} top ${fontMetrics.top} bottom ${fontMetrics.bottom}")
}
输出结果
System.out: descent 87.890625 ascent -333.98438 top -380.21484 bottom 97.55859
效果图
关于绘制文字的5条线
ascent: 系统建议的,绘制单个字符时,字符应当的最高高度所在线
descent:系统建议的,绘制单个字符时,字符应当的最低高度所在线
top: 可绘制的最高高度所在线
bottom: 可绘制的最低高度所在线
可以看到用fontMetrics这种方法是贴不了顶的,因为descent,ascent,top,bottom并不是文字真实的绘制区域
那么要贴顶的话就要第二种测量方法了
2.paint.getTextBounds
用法
private val bounds = Rect()
private val paint = Paint().apply {
isAntiAlias = true
textSize = 120.dp
style = Paint.Style.FILL
}
@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
paint.getTextBounds("qwer", 0, "qwer".length, bounds)
println("top ${bounds.top} bottom ${bounds.bottom} left ${bounds.left} right ${bounds.right}")
canvas.drawText("qwer", 0f, (-bounds.top).toFloat(), paint)
}
输出结果
System.out: top -197 bottom 74 left 11 right 786
效果图
贴顶了,bounds的4个值是真实绘制的区域
注意:以上纯属记录