如何使动态创建的位图适合ImageView?

时间:2016-05-02 12:10:55

标签: java android android-imageview android-bitmap

我希望使用给定文字大小的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

的src
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?

1 个答案:

答案 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;
}