Skip to content

Draw a scaled Bitmap to the Canvas?

The following code defines my Bitmap:

Resources res = context.getResources();

mBackground = BitmapFactory.decodeResource(res, R.drawable.background);

// scale bitmap
int h = 800; // height in pixels
int w = 480; // width in pixels
// Make sure w and h are in the correct order
Bitmap scaled = Bitmap.createScaledBitmap(mBackground, w, h, true);

… And the following code is used to execute/draw it (the unscaled Bitmap):

canvas.drawBitmap(mBackground, 0, 0, null);

My question is, how might I set it to draw the scaled Bitmap returned in the form of Bitmap scaled, and not the original?

Answer

Define a new class member variable: Bitmap mScaledBackground; Then, assign your newly created scaled bitmap to it: mScaledBackground = scaled; Then, call in your draw method: canvas.drawBitmap(mScaledBackground, 0, 0, null);

Note that it is not a good idea to hard-code screen size in the way you did in your snippet above. Better would be to fetch your device screen size in the following way:

int width = getWindowManager().getDefaultDisplay().getWidth();
int height = getWindowManager().getDefaultDisplay().getHeight();

And it would be probably better not to declare a new bitmap for the only purpose of drawing your original background in a scaled way. Bitmaps consume a lot of precious resources, and usually a phone is limited to a few MB of Bitmaps you can load before your app ungracefully fails. Instead you could do something like this:

Rect src = new Rect(0, 0, bitmap.getWidth() - 1, bitmap.getHeight() - 1);
Rect dest = new Rect(0, 0, width - 1, height - 1);
canvas.drawBitmap(mBackground, src, dest, null);