我们都知道Android的文本有个baseline,但是具体是什么大多数人应该都是含糊其词,用到时候位置重视感觉不能居中,我也记录一下
先看一张图:
上面有很多的标记,大家可能对基本的结构就已经清楚了,可以看到baseline的位置位于中间偏下的位置,这就是大家有时候无法居中的主要原因;
如何获取图片中的各个位置,Paint提供了方法:Paint.FontMetrics
查看代码:
public static class FontMetrics {
/**
* The maximum distance above the baseline for the tallest glyph in
* the font at a given text size.
*/
public float top;
/**
* The recommended distance above the baseline for singled spaced text.
*/
public float ascent;
/**
* The recommended distance below the baseline for singled spaced text.
*/
public float descent;
/**
* The maximum distance below the baseline for the lowest glyph in
* the font at a given text size.
*/
public float bottom;
/**
* The recommended additional space to add between lines of text.
*/
public float leading;
}
可以看到里面有这么几个值;就是对应上面的值
- 基准点是baseline
- Ascent是baseline之上至字符最高处的距离
- Descent是baseline之下至字符最低处的距离
- Leading 文本件空白距离
- Top指的是指的是最高字符到baseline的值,即ascent的最大值
- 同上,bottom指的是最下字符到baseline的值,即descent的最大值
打印一下基本的值:
fontMetrics.ascent:-30.615234 descent.top:-34.853027 fontMetrics.descent:8.056641 fontMetrics.bottom:8.942871
通过打印值可以看出baseline上面的为负值baseline下面的为正值,也可以看到ascent跟top,descent跟bottom是有一定的差别的,对比上图大家应该能明白差别的原因;
上一个居中的例子:
@Override
public void onDraw (Canvas canvas) {
Rect targetRect = new Rect(0, 0, 1000, 1000);
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setStrokeWidth(4f);
paint.setTextSize(80f);
String testString = "Hello,world";
paint.setColor(Color.GRAY);
canvas.drawRect(targetRect, paint);
paint.setColor(Color.RED);
FontMetricsInt fontMetrics = paint.getFontMetricsInt();
int baseline = targetRect.top + (targetRect.bottom - targetRect.top ) / 2 - fontMetrics.top - (fontMetrics.bottom - fontMetrics.top) / 2;
// 下面这行是实现水平居中,drawText对应改为传入targetRect.centerX()
paint.setTextAlign(Paint.Align.CENTER);
canvas.drawText(testString, targetRect.centerX(), baseline, paint);
}