2

I'd like to create a Bitmap from a String with a given text size and set it as source of an ImageView.

The ImageView in it's layout xml:

<ImageView
    android:id="@+id/myImageView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:scaleType="fitXY"/>

Setting the Bitmap as src of the ImageView:

myImageView.setImageBitmap(getBitmapFromString("StringToDraw", 30));

My getBitmapFromString method:

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

How can i calculate the proper size for the Bitmap (from the given text size and String length) and how can i make it to fit the ImageView properly?

1 Answers1

0

Found the solution in the following answer to a similar question: https://stackoverflow.com/a/15252876/3363481

My code looks like this now:

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;
}
Community
  • 1
  • 1
earthw0rmjim
  • 19,027
  • 9
  • 49
  • 63