Skip to content

@samsonjs /scale.java
Created

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.