Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Draw a scaled bitmap to the canvas?

Tags:

java

android

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?

like image 940
tadamson Avatar asked May 02 '12 02:05

tadamson


People also ask

How do you make a Bitmap on canvas?

Use the Canvas method public void drawBitmap (Bitmap bitmap, Rect src, RectF dst, Paint paint) . Set dst to the size of the rectangle you want the entire image to be scaled into. EDIT: Here's a possible implementation for drawing the bitmaps in squares across on the canvas.

What is a Bitmap canvas?

Canvas is the place or medium where perfroms/executes the operation of drawing, and Bitmap is responsible for storing the pixel of the picture you draw.

How to create Bitmap in Android?

To create a bitmap from a resource, you use the BitmapFactory method decodeResource(): Bitmap bitmap = BitmapFactory. decodeResource(getResources(), R. drawable.


1 Answers

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);
like image 192
epichorns Avatar answered Oct 22 '22 17:10

epichorns