Paint.FontMetrics
top, bottom, ascent, decent 皆以baseline为基准计算,所以top, ascent为负数
- top:给定文本大小的字体中最高字形在基线之上的最大距离。
- ascent:高于基线的推荐距离。
- decent:对于单独间隔的文本,建议低于基线的距离。
- bottom:在给定文本大小下,字体中最低字形低于基线的最大距离。
- leading:建议在文本行之间添加的额外空间。(行距)
字体高度一般用 decent - ascent
效果图(Y为baseline)
override fun onDraw(canvas: Canvas?) {
super.onDraw(canvas)
canvas?.also {
val str = "abcdefg字体?∑"
val x = 300f
val y = 200f
val textPaint = Paint()
textPaint.textSize = 75f
textPaint.color = 0xff3060f0.toInt()
val fontMetrics = textPaint.getFontMetrics()
it.drawText(str, x, y, textPaint)
paint.textSize = 45f
paint.color = 0xff303030.toInt()
it.drawLine(x, 0f, x, height.toFloat(), paint)
it.drawLine(x, y, width.toFloat(), y, paint)
it.drawText("XY", 10f, 60f, paint)
paint.color = 0xff30f030.toInt()
it.drawLine(x, y+fontMetrics.top, width.toFloat(), y+fontMetrics.top, paint)
it.drawLine(x, y+fontMetrics.bottom, width.toFloat(), y+fontMetrics.bottom, paint)
it.drawText("Y+Top", 10f, 120f, paint)
it.drawText("Y+Bottom", 10f, 180f, paint)
paint.color = 0xfff030f0.toInt()
it.drawLine(x, y+fontMetrics.ascent, width.toFloat(), y+fontMetrics.ascent, paint)
it.drawLine(x, y+fontMetrics.descent, width.toFloat(), y+fontMetrics.descent, paint)
it.drawText("Y+ascent", 10f, 240f, paint)
it.drawText("Y+decent", 10f, 300f, paint)
Log.e(TAG, "onDraw() X:\t" + x)
Log.e(TAG, "onDraw() Y:\t" + y)
Log.e(TAG, "onDraw() fontMetrics ascent:\t" + fontMetrics.ascent)
Log.e(TAG, "onDraw() fontMetrics bottom:\t" + fontMetrics.bottom)
Log.e(TAG, "onDraw() fontMetrics descent:\t" + fontMetrics.descent)
Log.e(TAG, "onDraw() fontMetrics leading:\t" + fontMetrics.leading)
Log.e(TAG, "onDraw() fontMetrics top:\t" + fontMetrics.top)
}
}