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

前面例子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);



 


 


 

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值