Skip to content

Instantly share code, notes, and snippets.

@Viyu
Created July 31, 2015 02:58
Show Gist options
  • Save Viyu/19e02d0fa370cba727ae to your computer and use it in GitHub Desktop.
Save Viyu/19e02d0fa370cba727ae to your computer and use it in GitHub Desktop.
Scale the short side of the bitmap to goal value and limit the long side to the limit value.
/**
* 把小边放大至要求值,同时限制大边不超过要求值
*
* @param bitmap
* @param shortSideGoal
* 短边需要放大到的目标值
* @param longSideLimit
* 长边需要被限制的值得
* @return
*/
public static Bitmap scaleShortAndLimitLong(Bitmap bitmap, float shortSideGoal, float longSideLimit) {
if (bitmap == null) {
return null;
}
if (bitmap.isRecycled()) {
return null;
}
if (shortSideGoal < Math.min(bitmap.getWidth(), bitmap.getHeight())) {
return bitmap;
}
float sx = 1.0f;
float sy = 1.0f;
if (bitmap.getWidth() > bitmap.getHeight()) {// 如果y方向是短边
sy = shortSideGoal / bitmap.getHeight();
sx = sy;
if (bitmap.getWidth() * sx > longSideLimit) {
sx = longSideLimit / bitmap.getWidth();
}
} else {// 如果x方向是短边
sx = shortSideGoal / bitmap.getWidth();
sy = sx;
if (bitmap.getHeight() * sy > longSideLimit) {
sy = longSideLimit / bitmap.getHeight();
}
}
Matrix matrix = new Matrix();
matrix.postScale(sx, sy);
Bitmap resizeBmp = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
return resizeBmp;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment