Skip to content Skip to sidebar Skip to footer

Draw A Scaled Bitmap To The Canvas?

The following code defines my bitmap: Resources res = context.getResources(); mBackground = BitmapFactory.decodeResource(res, R.drawable.bg2); //scale bitmap

Solution 1:

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: c.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:

Rectsrc=newRect(0,0,bitmap.getWidth()-1, bitmap.getHeight()-1);
Rectdest=newRect(0,0,width-1, height-1);
c.drawBitmap(mBackground, src, dest, null);

Solution 2:

To draw the scaled bitmap you want save your scaled bitmap in a field somewhere (here called mScaled) and call:

    c.drawBitmap(mScaled,0,0,null);

in your draw method (or wherever you call it right now).

Post a Comment for "Draw A Scaled Bitmap To The Canvas?"