Created
September 10, 2012 20:13
-
-
Save samsonjs/3693545 to your computer and use it in GitHub Desktop.
Scale a Bitmap preserving the aspect ratio
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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
Worked flawlessly, thanks! :P