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

本文介绍了一种用于中心裁剪并按固定宽度缩放图片的方法。该方法首先计算目标尺寸,然后创建一个缩小版的图片,最后从中裁剪出符合高度要求的部分。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/**
* 缩放截取宽度固定高度正中部分后的位图。
*
* @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"
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值