public
Created

Scale a Bitmap preserving the aspect ratio

  • Download Gist
scale.java
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
// Scale a bitmap preserving the aspect ratio.
private Bitmap scale(Bitmap bitmap, int maxWidth, int maxHeight) {
// Determine the constrained dimension, which determines both dimensions.
int width;
int height;
float widthRatio = (float)bitmap.getWidth() / maxWidth;
float heightRatio = (float)bitmap.getHeight() / maxHeight;
// Width constrained.
if (widthRatio >= heightRatio) {
width = maxWidth;
height = (int)(((float)width / bitmap.getWidth()) * bitmap.getHeight());
}
// Height constrained.
else {
height = maxHeight;
width = (int)(((float)height / bitmap.getHeight()) * bitmap.getWidth());
}
Bitmap scaledBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
 
float ratioX = (float)width / bitmap.getWidth();
float ratioY = (float)height / bitmap.getHeight();
float middleX = width / 2.0f;
float middleY = height / 2.0f;
Matrix scaleMatrix = new Matrix();
scaleMatrix.setScale(ratioX, ratioY, middleX, middleY);
 
Canvas canvas = new Canvas(scaledBitmap);
canvas.setMatrix(scaleMatrix);
canvas.drawBitmap(bitmap, middleX - bitmap.getWidth() / 2, middleY - bitmap.getHeight() / 2, new Paint(Paint.FILTER_BITMAP_FLAG));
return scaledBitmap;
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.