Skip to content

Commit a086473

Browse files
committed
Update
1 parent 1b9d3b5 commit a086473

1 file changed

Lines changed: 27 additions & 0 deletions

File tree

‎CustomView/Advance/[7]DrawText.md‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -221,12 +221,39 @@ leading | + | 行间距,当前行bottom与下一行top之间的距离的推荐
221221

222222
而让文字垂直居中则有些麻烦了,因为BaseLineY既不是顶部,底部,也不是中心,所以文本居中最难的内容就是计算BaseLineY的位置。
223223

224+
我们已知:
224225

226+
> 1. 中心位置坐标,centerX, centerY
227+
2. 文本高度:height = descent-ascent
228+
3. descent的坐标:descentY = centerY + 1/2height
229+
4. baseLineY坐标:baseLineY = descentY-descent
225230

231+
通过上面内容可以推算出如下公式:
226232

233+
> baseLineY = centerY - 1/2(ascent + descent)
227234
235+
**根据公式我们可以封装一个方法:**
228236

237+
``` java
238+
/**
239+
* 居中绘制文本
240+
*
241+
* @param text
242+
* @param canvas
243+
* @param paint
244+
*/
245+
public void drawTextByCenter(String text, float x, float y, Canvas canvas, Paint paint) {
246+
Paint tempPaint = new Paint(paint); // 创建一个临时画笔,防止影响原来画笔的状态
247+
tempPaint.setTextAlign(Paint.Align.CENTER); // 设置文本对齐方式为居中
248+
249+
// 通过y计算出baseline的位置
250+
float baseline = y - (tempPaint.descent() + tempPaint.ascent()) / 2;
251+
252+
canvas.drawText(text, x, baseline, tempPaint); //绘制文本
253+
}
254+
```
229255

256+
**测试方法是否正确**
230257

231258

232259

0 commit comments

Comments
 (0)