过程
- 计算字符串绘制成图片时的图片大小
- 创建位图
- 绘制位图
代码
public static Bitmap fromText(float textSize, String text) {
Paint paint = new Paint();
paint.setTextSize(textSize);
paint.setTextAlign(Paint.Align.LEFT);
paint.setColor(Color.BLACK);
Rect bound = new Rect();
paint.getTextBounds(text, 0, text.length(), bound);
Paint.FontMetrics fm = paint.getFontMetrics();
int width = bound.width() + 6;
int height = bound.height() + 4;
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
canvas.drawText(text, 0, height + fm.top - fm.ascent, paint);
canvas.save();
return bitmap;
}
示例
将货币符号转成位图显示在控件左侧,将金额作为控件的文本值,可以使控件更好的表示金钱的概念
Currency currency = Currency.getInstance("USD");
Bitmap bitmap = fromText(36, currency.getSymbol());
Drawable drawable = new BitmapDrawable(bitmap);
drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
view.setCompoundDrawables(drawable , null, null, null);
网友评论