Ragunath Jawahar
Ragunath Jawahar

Reputation: 19723

Determine width and height of a bitmap

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.

Upvotes: 1

Views: 1024

Answers (2)

Bill Gary
Bill Gary

Reputation: 3005

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();

Upvotes: 1

Roman Black
Roman Black

Reputation: 3497

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

Upvotes: 1

Related Questions