当前位置:操作系统 > 安卓/Android >>

Android ApiDemos示例解析(81):Graphics->Text Align

前面例子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.zzzyk.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
补充:移动开发 , Android ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,