3 回答
TA贡献1872条经验 获得超3个赞
我对度量大小进行了一些更改,因此位图将支持不同的字体大小。它仅支持单行文本。
public static Bitmap getFontBitmap(Context context, String text, int color, float fontSizeSP) {
int fontSizePX = convertDiptoPix(context, fontSizeSP);
int pad = (fontSizePX / 9);
Paint paint = new Paint();
Typeface typeface = Typeface.createFromAsset(context.getAssets(), "Fonts/Roboto-Regular.ttf");
paint.setAntiAlias(true);
paint.setTypeface(typeface);
paint.setColor(color);
paint.setTextSize(fontSizePX);
int textWidth = (int) (paint.measureText(text) + pad * 2);
int height = (int) (fontSizePX / 0.75);
Bitmap bitmap = Bitmap.createBitmap(textWidth, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
float xOriginal = pad;
canvas.drawText(text, xOriginal, fontSizePX, paint);
return bitmap;
}
public static int convertDiptoPix(Context context, float dip) {
int value = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dip, context.getResources().getDisplayMetrics());
return value;
}
- 3 回答
- 0 关注
- 519 浏览
添加回答
举报