bitmap缩放剪裁图片(等宽裁中间部分高)

来源:互联网 发布:编程机器人手机中文版 编辑:程序博客网 时间:2024/05/04 15:55
/**
* 缩放截取宽度固定高度正中部分后的位图。
*
* @param bitmap 原图
*/
public static Bitmap centerRectangleBitmap(Bitmap bitmap) {
final int edgeWidth = (int) (App.screenWidth - 26 * App.mDensity) / 2;//view的宽度是屏幕宽度的一半
final int edgeLength = (int) (edgeWidth / 1.5);//view的高度是宽度的2/3
if (null == bitmap || edgeLength <= 0) {
return null;
}

Bitmap result = bitmap;
int widthOrg = bitmap.getWidth();
int heightOrg = bitmap.getHeight();
// 压缩到一个最小长度是edgeLength的bitmap
int longerEdge = (int) (edgeWidth * Math.max(widthOrg, heightOrg) / Math
.min(widthOrg, heightOrg));
int scaledWidth = widthOrg >= heightOrg ? longerEdge : edgeWidth;
Bitmap scaledBitmap = null;

try {
scaledBitmap = Bitmap.createScaledBitmap(bitmap, scaledWidth,
scaledWidth, true);
} catch (Exception e) {
return null;
}

if (heightOrg >= edgeLength) {
// 从图中截取正中间的高。
int yTopLeft = (scaledWidth - edgeLength) / 2;
try {
if (scaledBitmap != null) {
result = Bitmap.createBitmap(scaledBitmap, 0,
yTopLeft, scaledWidth, edgeLength);
scaledBitmap.recycle();
}
} catch (Exception e) {
return null;
}
}
return result;
}
注:需配合android:scaleType="centerCrop"
0 0
原创粉丝点击