`
xixinfei
  • 浏览: 410317 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

Canvas drawText

阅读更多

String str ="测试字符串";

  int len = str.getBytes().length;
  int w = len *16;
  int h =32;
  Bitmap strBitmap =Bitmap.createBitmap(w, h,Bitmap.Config.RGB_565);
  Canvas c =newCanvas(strBitmap);
  Paint paint =newPaint(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");
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics