前言:
在我们做界面开发的时候,UI的标注图中经常是标注了文字的字号和文件的间距。而当我们使用多个TextView 实现后,却发现textView 之间的空白区域的高度,是远大于设计标注的。
前提: TextView height = warp_content。 设为单行。
原因: TextView 高度包含 1) IncludedFontPadding 2,Line height;
而LineHeight 也并不是文字字号高度,并且也大于字号高度。
TextView textView = (TextView) findViewById(R.id.sample_text); textView.setBackgroundColor(Color.YELLOW); textView.setTextSize(TypedValue.COMPLEX_UNIT_PX , 60);
1,关于行高获取:
int ht = textView.getLineHeight();
这个高度的获取,并不需要对当前的Text 进行测量。 与当前的TextSize 正相关。
2,
textView.setIncludeFontPadding(false);
可以通过这个方法,禁掉首行文字和末行文字的font padding。
3, 关于文字绘制与行高
public class MText extends TextView{ public MText(Context context) { super(context); } public MText(Context context, @Nullable AttributeSet attrs) { super(context, attrs); } public MText(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @Override public void onDraw(Canvas canvas){ super.onDraw(canvas);// FontMetrics对象 Paint textPaint = getPaint(); Paint.FontMetrics fontMetrics = textPaint.getFontMetrics();// 计算每一个坐标 float baseX = 0; float baseY = getBaseline(); float topY = baseY + fontMetrics.top; float ascentY = baseY + fontMetrics.ascent; float descentY = baseY + fontMetrics.descent; float bottomY = baseY + fontMetrics.bottom;// BaseLine描画 Paint baseLinePaint = new Paint( Paint.ANTI_ALIAS_FLAG); baseLinePaint.setColor( Color.RED); canvas.drawLine(0, baseY, getWidth(), baseY, baseLinePaint);// Base描画 canvas.drawCircle( baseX, baseY, 5, baseLinePaint);// TopLine描画 Paint topLinePaint = new Paint( Paint.ANTI_ALIAS_FLAG); topLinePaint.setColor( Color.LTGRAY); canvas.drawLine(0, topY, getWidth(), topY, topLinePaint);// AscentLine描画 Paint ascentLinePaint = new Paint( Paint.ANTI_ALIAS_FLAG); ascentLinePaint.setColor( Color.GREEN); canvas.drawLine(0, ascentY, getWidth(), ascentY, ascentLinePaint);// DescentLine描画 Paint descentLinePaint = new Paint( Paint.ANTI_ALIAS_FLAG); descentLinePaint.setColor( Color.YELLOW); canvas.drawLine(0, descentY, getWidth(), descentY, descentLinePaint);// ButtomLine描画 Paint bottomLinePaint = new Paint( Paint.ANTI_ALIAS_FLAG); bottomLinePaint.setColor( Color.MAGENTA); canvas.drawLine(0, bottomY, getWidth(), bottomY, bottomLinePaint); }}
文字的行高计算:
float ascentY = baseY + fontMetrics.ascent;float descentY = baseY + fontMetrics.descent;
int lineHeght = descentY - ascentY; //[不是从源码得出的结论,待进一步验证]
参考:
https://blog.csdn.net/l732427480/article/details/51711970