一、這個圖是錯誤的
這個 leading 的標記是不對的。
二、正確的圖
三、小編的圖
四、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
九、疑惑
Top 和 ascent 之見有什麼用途,希望各位夥伴可以告知。