Android ApiDemos樣本解析(81):Graphics->Text Align

來源:互聯網
上載者:User

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.