参考图:
四、14SP的TextView,在三倍机上,高度是57px
五、FontMetrics的字段值
大约好像 top + bottom ≈ 高度。具体的计算需要看源码,但是从理论上来说,textView的高度 是 Top 和 Bottom 的距离。
六、字段定义
https://developer.android.com/reference/android/graphics/Paint.FontMetrics
七:代码
大家自定义一个TextView,把小编这段代码放进去就行
```
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int measuredHeight = getMeasuredHeight();
int measuredWidth = getMeasuredWidth();
Log.i("高度", measuredHeight + "");
TextPaint paint = getPaint();
Paint.FontMetrics fontMetrics = paint.getFontMetrics();
float ascent = fontMetrics.ascent;
float descent = fontMetrics.descent;
float leading = fontMetrics.leading;
float top = fontMetrics.top;
float bottom = fontMetrics.bottom;
Log.i("高度", ascent + " ascent");
Log.i("高度", descent + " descent");
Log.i("高度", leading + " leading");
Log.i("高度", top + " top");
Log.i("高度", bottom + " bottom");
Paint paint1 = new Paint();
paint1.setAntiAlias(true);
paint1.setStrokeWidth(1);
// TOP
paint1.setColor(resources.getColor(R.color._E47833));
canvas.drawLine(0, 0, measuredWidth, 0, paint1);
// ascent
paint1.setColor(resources.getColor(R.color._2F2F4F));
canvas.drawLine(0, -top + ascent, measuredWidth, -top + ascent, paint1);
// baseLine
paint1.setColor(resources.getColor(R.color._238E23));
canvas.drawLine(0, -top, measuredWidth, -top, paint1);
// descent
paint1.setColor(resources.getColor(R.color._8E2323));
canvas.drawLine(0, -ascent + descent, measuredWidth, -ascent + descent, paint1);
// bottom
paint1.setColor(resources.getColor(R.color._FF6EC7));
canvas.drawLine(0, -top + bottom, measuredWidth, -top + bottom , paint1);
}
```
八:结论
自定义TextView 时候,如果需要在 onMeasure中 重写 wrap_content 的mode 情况,可以考虑 Top + Bottom 为控件高度。
而在 onDraw 中,文本绘制时,使用 ascent + bottom 为 文字高度,而我们常用的时候,可以 ascent + dscent