Last active
August 1, 2019 10:58
-
-
Save yushaojian13/9a055a60208e3f28e34d0bc4e033e278 to your computer and use it in GitHub Desktop.
A bitmap util that scale source bitmap to specific size with aspect ratio remained, alpha pixels filled on one dimension if need
This file contains hidden or 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
public class BitmapUtils { | |
/** | |
* scale source bitmap to specific width and height remaining the aspect ratio. | |
* If source bitmap aspect ratio is not the same with target ((float) dstWidth / dstHeight), | |
* then one dimension will scaled to the target value, and another will be filled with 0 alpha pixels | |
* | |
* @param src source bitmap | |
* @param dstWidth target width | |
* @param dstHeight target height | |
* @param filter true if the source should be filtered. | |
* @return target bitmap | |
*/ | |
public static Bitmap createScaledBitmapAspectRatioKept(Bitmap src, int dstWidth, int dstHeight, boolean filter) { | |
final Bitmap dstBitmap = Bitmap.createBitmap(dstWidth, dstHeight, Bitmap.Config.ARGB_8888); | |
final Canvas canvas = new Canvas(dstBitmap); | |
final float srcWidth = src.getWidth(); | |
final float srcHeight = src.getHeight(); | |
final float xScale = dstWidth / srcWidth; | |
final float yScale = dstHeight / srcHeight; | |
final float scale = Math.min(xScale, yScale); | |
final Matrix matrix = new Matrix(); | |
final float xTranslation; | |
final float yTranslation; | |
if (xScale < yScale) { | |
xTranslation = 0.0f; | |
yTranslation = (dstHeight - srcHeight * scale) / 2.0f; | |
} else { | |
xTranslation = (dstWidth - srcWidth * scale) / 2.0f; | |
yTranslation = 0.0f; | |
} | |
matrix.postTranslate(xTranslation, yTranslation); | |
matrix.preScale(scale, scale); | |
Paint paint = new Paint(); | |
paint.setFilterBitmap(filter); | |
paint.setAntiAlias(!matrix.rectStaysRect()); | |
canvas.drawBitmap(src, matrix, paint); | |
return dstBitmap; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment