android+bitmap+drawtext,Android之Canvas DrawText

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");

0b1331709591d260c1c78e86d0c51c18.png

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值