本文最后更新于 93 天前,其中的信息可能已经有所发展或是发生改变。
1. 单行文本
FontMetrics.ascent 或 Paint.ascent 注意这些都是间距
ascent = ascent线的y坐标 - baseline线的y坐标; // 为负值
descent = descent线的y坐标 - baseline线的y坐标;
top = top线的y坐标 - baseline线的y坐标;
bottom = bottom线的y坐标 - baseline线的y坐标;
center先计算
float centerY
= (fontmetrics.descent - fontmetrics.ascent) / 2 - fontmetrics.descent;
= -fontmetrics.ascent / 2 - fontmetrics.descent / 2;
= -(fontmetrics.ascent + fontmetrics.descent) / 2;
= math.abs(fontmetrics.ascent + fontmetrics.descent) / 2;
canvas.drawText(text, x, y – ((paint.descent() + paint.ascent()) / 2), paint);
public void draw(canvas canvas) {
super.draw(canvas);
// 将坐标原点移到控件中心
canvas.translate(getwidth() / 2, getheight() / 2);
// x轴
canvas.drawline(-getwidth() / 2, 0, getwidth() / 2, 0, paint);
// y轴
canvas.drawline(0, -getheight() / 2, 0, getheight() / 2, paint);
// 绘制居中文字
paint.settextsize(sp2px(50));
paint.setcolor(color.gray);
// 文字宽
float textwidth = paint.measuretext("yangle'blog");
// 文字baseline在y轴方向的位置
float baseliney = math.abs(paint.ascent() + paint.descent()) / 2;
canvas.drawtext("yangle'blog", -textwidth / 2, baseliney, paint);
}
2. 多行文本
– 文本在x轴上方:红色a的baseline向上移动a距离,总高度的/2 – 文本的top值(绝对值)
– 文本在x轴中间:红色a的baseline向下移动b距离,计算公式请参考单行文本居中公式
– 文本在x轴下方:红色a的baseline向下移动c距离,总高度的/2 – 文本的bottom值(绝对值)
private void drawcentermultitext2(canvas canvas) {
string[] texts = {"a", "b", "c"};
paint.fontmetrics fontmetrics = paint.getfontmetrics();
// top绝对值
float top = math.abs(fontmetrics.top);
// ascent绝对值
float ascent = math.abs(fontmetrics.ascent);
// descent,正值
float descent = fontmetrics.descent;
// bottom,正值
float bottom = fontmetrics.bottom;
// 行数
int textlines = texts.length;
// 文本高度
float textheight = top + bottom;
// 文本总高度
float texttotalheight = textheight * textlines;
// 基数
float baseposition = (textlines - 1) / 2f;
for (int i = 0; i < textlines; i++) {
// 文本宽度
float textwidth = paint.measuretext(texts[i]);
// 文本baseline在y轴方向的位置
float baseliney;
if (i < baseposition) {
// x轴上,值为负
// 总高度的/2 - 已绘制的文本高度 - 文本的top值(绝对值)
baseliney = -(texttotalheight / 2 - textheight * i - top);
} else if (i > baseposition) {
// x轴下,值为正
// 总高度的/2 - 未绘制的文本高度 - 文本的bottom值(绝对值)
baseliney = texttotalheight / 2 - textheight * (textlines - i - 1) - bottom;
} else {
// x轴中,值为正
// 计算公式请参考单行文本居中公式
baseliney = (ascent - descent) / 2;
}
canvas.drawtext(texts[i], -textwidth / 2, baseliney, paint);
}
}