前面例子Android ApiDemos樣本解析(68):Graphics->MeasureText 介紹了如何取的所繪製文字串的尺寸(寬度和高度),文字的預設對齊為靠左對齊,本例介紹了其它幾種對齊:Left, Center ,Right 以及如何沿任意曲線繪製文字。
Paint的getTextWidths 方法取得字串中每個字元的寬度:
[java]
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;
}
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:
[java]
p.setTextAlign(Paint.Align.LEFT);
...
p.setTextAlign(Paint.Align.CENTER);
...
p.setTextAlign(Paint.Align.RIGHT);
canvas.drawText(TEXT_R, x, y, p);
p.setTextAlign(Paint.Align.LEFT);
...
p.setTextAlign(Paint.Align.CENTER);
...
p.setTextAlign(Paint.Align.RIGHT);
canvas.drawText(TEXT_R, x, y, p);建立一條路徑makePath
[java]
private static void makePath(Path p) {
p.moveTo(10, 0);
p.cubicTo(100, -50, 200, 50, 300, 0);
}
private static void makePath(Path p) {
p.moveTo(10, 0);
p.cubicTo(100, -50, 200, 50, 300, 0);
}然後沿這條路徑,也以三種不同對齊沿Path繪製文字:
[java]
p.setTextAlign(Paint.Align.LEFT);
...
p.setTextAlign(Paint.Align.CENTER);
...
p.setTextAlign(Paint.Align.RIGHT);
canvas.drawPath(mPath, mPathPaint); www.2cto.com
canvas.drawTextOnPath(TEXTONPATH, mPath, 0, 0, p);
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);
作者:mapdigit