前面例子Android ApiDemos示例解析(68):Graphics->MeasureText 介绍了如何取的所绘制文字串的尺寸(宽度和高度),文字的缺省对齐为左对齐,本例介绍了其它几种对齐方式:Left, Center ,Right 以及如何沿任意曲线绘制文字。
Paint的getTextWidths 方法取得字符串中每个字符的宽度:
private float[] buildTextPositions(String text,
float y, Paint paint) {
float[] widths = new float1;
// initially get the widths for each char
int n = paint.getTextWidths(text, widths);
// now popuplate the array,
//interleaving spaces for the Y values
float[] pos = new float[n * 2];
float accumulatedX = 0;
for (int i = 0; i < n; i++) {
pos[i*2 + 0] = accumulatedX;
pos[i*2 + 1] = y;
accumulatedX += widths[i];
}
return pos;
}
然后使用三种不同对齐方式绘制文字:Left,Center,Right:
p.setTextAlign(Paint.Align.LEFT);
...
p.setTextAlign(Paint.Align.CENTER);
...
p.setTextAlign(Paint.Align.RIGHT);
canvas.drawText(TEXT_R, x, y, p);
创建一条路径makePath
private static void makePath(Path p) {
p.moveTo(10, 0);
p.cubicTo(100, -50, 200, 50, 300, 0);
}
然后沿这条路径,也以三种不同对齐方式沿Path绘制文字:
p.setTextAlign(Paint.Align.LEFT);
...
p.setTextAlign(Paint.Align.CENTER);
...
p.setTextAlign(Paint.Align.RIGHT);
canvas.drawPath(mPath, mPathPaint);
canvas.drawTextOnPath(TEXTONPATH, mPath, 0, 0, p);