Skip to content

Commit

Permalink
Merge pull request alidili#3 from Tao93/master
Browse files Browse the repository at this point in the history
改进第二种绘制多行居中文本的代码
  • Loading branch information
alidili authored Feb 11, 2018
2 parents 4e53adf + 00fe039 commit 5ec1c3f
Showing 1 changed file with 10 additions and 37 deletions.
47 changes: 10 additions & 37 deletions DrawTextDemo/app/src/main/java/com/yl/drawtext/CustomTextView.java
Original file line number Diff line number Diff line change
Expand Up @@ -144,46 +144,19 @@ 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;

// 文本高度
float textHeight = fontMetrics.bottom - fontMetrics.top;
// 行数
int textLines = texts.length;
// 文本高度
float textHeight = top + bottom;
// 文本总高度
float textTotalHeight = textHeight * textLines;
// 基数
float basePosition = (textLines - 1) / 2f;

for (int i = 0; i < textLines; i++) {
// 文本宽度
// 中间一行文本的 base line
float centerBaseY = -(fontMetrics.ascent + fontMetrics.descent) / 2;
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);
// 第 i 行文字的 base line = 中间一行的 base line + 偏移
// 而偏移等于行号的偏移 * textHeight,行号偏移等于 i 减去中间一行的行号,即减去 (textLines - 1) / 2
float baseY = centerBaseY + (i - (textLines - 1) / 2.0f) * textHeight;
canvas.drawText(texts[i], -textWidth / 2, baseY, paint);
}
}

Expand Down

0 comments on commit 5ec1c3f

Please sign in to comment.