Friday, January 20, 2012

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.

2 comments:

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

    ReplyDelete
  2. 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();

    ReplyDelete