我正在尝试将字符串转换为位图,最后我找到了解决方案:
public static Bitmap textToBitmap(Context c, String text, String typeface, int size, int color){
Paint paint = new Paint();
paint.setTextSize(size);
paint.setTextAlign(Paint.Align.LEFT);
paint.setAntiAlias(true);
paint.setSubpixelText(true);
paint.setColor(color);
Typeface tf = Typeface.createFromAsset(c.getAssets(),typeface);
paint.setTypeface(tf);
int width = (int) (paint.measureText(text) + 0.5f); // round
float baseline = (int) (paint.ascent()*(0.80f) + 0.5f);
int height = (int) (paint.descent()*(0.5f) - paint.ascent()*(0.70f) + 0.5f);
Bitmap image = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
int y = (int) (baseline*(-1));
Canvas canvas = new Canvas(image);
canvas.drawText(text, 0, y, paint);
return image;
}
我的问题是这个解决方案不适用于所有屏幕(因为宽度和高度不正确)并且有点粗糙。
有没有最好的代码来做到这一点?
非常感谢...