Skip to content

Instantly share code, notes, and snippets.

@samsonjs
Created September 10, 2012 20:13
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save samsonjs/3693545 to your computer and use it in GitHub Desktop.
Save samsonjs/3693545 to your computer and use it in GitHub Desktop.
Scale a Bitmap preserving the aspect ratio
// 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;
}
@Nathcat
Copy link

Nathcat commented May 23, 2021

Worked flawlessly, thanks! :P

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment