我希望使用给定文字大小的Bitmap
创建String
,并将其设置为ImageView
的来源。
{x}中的ImageView
布局xml:
<ImageView
android:id="@+id/myImageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scaleType="fitXY"/>
将Bitmap
设置为ImageView
:
myImageView.setImageBitmap(getBitmapFromString("StringToDraw", 30));
我的getBitmapFromString
方法:
private Bitmap getBitmapFromString(String string, float textSize) {
Bitmap bitmap = Bitmap.createBitmap(200, 200, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setSubpixelText(true);
paint.setStyle(Paint.Style.FILL);
paint.setColor(Color.WHITE);
paint.setTextSize(textSize);
paint.setTextAlign(Paint.Align.LEFT);
canvas.drawText(string, 0, 100, paint);
return bitmap;
}
如何计算Bitmap的正确大小(来自给定的文本大小和String
长度)以及如何使其适合ImageView?
答案 0 :(得分:0)
在以下答案中找到类似问题的解决方案: https://stackoverflow.com/a/15252876/3363481
我的代码现在看起来像这样:
private Bitmap getBitmapFromString(String text, float fontSizeSP, Context context) {
int fontSizePX = convertDiptoPix(context, fontSizeSP);
int pad = (fontSizePX / 9);
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setColor(Color.WHITE);
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_4444);
Canvas canvas = new Canvas(bitmap);
float xOriginal = pad;
canvas.drawText(text, xOriginal, fontSizePX, paint);
return bitmap;
}