Tuesday, March 13, 2012

Android Note: Scale the bitmap and keep aspect ratio

In the previous post, Matrix.postScale() is used to draw the bitmap, but the result is not perfect. The aspect ratio of prepared bitmap is 1.67 (480x800), when scale it and draw on the screen with 1.5 aspect ratio (320x480), the width will be stretched.
To keep the aspect ratio, we can use Matrix.ScaleToFit.CENTER .

First, create two RectF obejct, one is for our prepared bitmap, another is for the target screen size.
RectF defaultRect = new RectF(0, 0, 480, 800);
RectF screenRect = new RectF(0, 0, 320, 480);
Then create and initialize the matrix
Matrix defToScreenMatrix = new Matrix();
defToScreenMatrix.setRectToRect(defaultRect, screenRect, Matrix.ScaleToFit.CENTER);
When the prepared bitmap is drawn on the screen canvas, we can apply the matrix and the scale result will keep the aspect ratio.
canvas.drawBitmap(preparedBitmap, defToScreenMatrix, null);
Let us look the example. PictureA indeed look better than PictureB.

PictureA (Matrix.ScaleToFit.CENTER)
PictureB (Matrix.postScale) 

No comments:

Post a Comment