1

I am using the following code snippet to create a bitmap with text.

Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG); 
paint.setStyle(Style.FILL);
paint.setColor(fontColor);
paint.setTextSize(fontSize);
canvas.drawText("My Text", x, y, paint);

Here's the catch. How do I determine the size of the Bitmap to use in the canvas beforehand? For instance if I want a bitmap with "Hello World!" on it, I want to find the width and height of it even before I draw the text on the canvas.

Simon Sarris
  • 62,212
  • 13
  • 141
  • 171
Ragunath Jawahar
  • 19,513
  • 22
  • 110
  • 155

2 Answers2

1

You can tyr this:

Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG); 

Rect bounds = new Rect();

paint.setStyle(Style.FILL);
paint.setColor(fontColor);
paint.setTextSize(fontSize);

paint.getTextBounds("My Text", 0, "My Text".length(), bounds);

int width = bounds.width();
int height = bounds.height();

canvas.drawText("My Text", x, y, paint);
Roman Black
  • 3,501
  • 1
  • 22
  • 31
1

Try this, it loads the bitmap, then gets the heigth and width, then you just have to draw it. Replace bitmap with your image name

bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.bitmap);
bitmapHeigth = bitmap.getHeigth();
bitmapWidth = bitmap.getWidth();
Bill Gary
  • 2,987
  • 2
  • 15
  • 19