I'm looking for a solution for the following problem: how to change the size of a Bitmap
to a fixed size (for example 512x128). The aspect ratio of the bitmap content must be preserved.
I think it should be something like this:
create an empty 512x128 bitmap
scale the original bitmap down to fit the 512x128 pixels with keeping the aspect ratio
copy the scaled into the empty bitmap (centered)
What is the simplest way to achieve this?
The reason for all this is, that the GridView
messes the layout up when the aspect ratio of an image differs from the other. Here is a screenshot (all images except the last one have the aspect ratio of 4:1):
Try this, calculate the ratio and then rescale.
private Bitmap scaleBitmap(Bitmap bm) {
int width = bm.getWidth();
int height = bm.getHeight();
Log.v("Pictures", "Width and height are " + width + "--" + height);
if (width > height) {
// landscape
float ratio = (float) width / maxWidth;
width = maxWidth;
height = (int)(height / ratio);
} else if (height > width) {
// portrait
float ratio = (float) height / maxHeight;
height = maxHeight;
width = (int)(width / ratio);
} else {
// square
height = maxHeight;
width = maxWidth;
}
Log.v("Pictures", "after scaling Width and height are " + width + "--" + height);
bm = Bitmap.createScaledBitmap(bm, width, height, true);
return bm;
}