本文共 1203 字,大约阅读时间需要 4 分钟。
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");
转载地址:https://blog.csdn.net/weixin_32667433/article/details/117677899 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!