歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android之Canvas DrawText

Android之Canvas DrawText

日期:2017/3/1 9:47:21   编辑:Linux編程

Android之Canvas DrawText

String str = "Hello";

int len = str.getBytes().length;
int w = len * 16;
int h = 32;
Bitmap strBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.RGB_565);
Canvas c = new Canvas(strBitmap);
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setTextSize(35);
Typeface tf = Typeface.createFromAsset(getAssets(), "caiyun");
paint.setTypeface(tf);
paint.setColor(0xFFFFFFFF);
paint.setTextAlign(Align.LEFT);

FontMetrics fm = paint.getFontMetrics();
c.drawText(str, 0, h + fm.top - fm.ascent, paint);
c.save();

其中 c.drawText(str, 0, h + fm.top - fm.ascent, paint);

是在指定位置開始輸出文字,而其中“h + fm.top - fm.ascent”就是這裡面的關鍵,h相當與一個參照(我這裡是要把文字寫到一個bitmap上,所以h就是bitmap的基准),fm.top - fm.ascent是開始輸出文字的baseline,不太明白的請看 Canvas.drawText的說明:Draw the text, with origin at (x,y), using the specified paint. The origin is interpreted based on the Align setting in the paint. Parameters:

text The text to be drawn

x The x-coordinate of the origin of the text being drawn

y The y-coordinate of the origin of the text being drawn

paint The paint used for the text (e.g. color, size, style)

這個origin就是文字baseline基線的坐標。

另外關於Typeface,比較遺憾是不太明白如何設置其他中文字體,比如宋體,楷體之類的,Typeface.createFromAsset(getAssets(), "caiyun");

更多Android相關信息見Android 專題頁面 http://www.linuxidc.com/topicnews.aspx?tid=11

Copyright © Linux教程網 All Rights Reserved