/**
* 按照指定的4:3比例,对源Bitmap进行裁剪
*
* @param srcBitmap 源图片对应的Bitmap
* @return Bitmap
*/
public static Bitmap centerCrop4To3(Bitmap srcBitmap) {
int desWidth = srcBitmap.getWidth();
int desHeight = srcBitmap.getHeight();
float desRate = (float) desWidth / desHeight;
float rate = 4f / 3f;
if (desRate > rate) {//宽有多余
desWidth = (int) (desHeight * 4 / 3);
} else {//宽有不够,裁剪高度
desHeight = (int) (desWidth * 3 / 4);
}
return centerCrop(srcBitmap, desWidth, desHeight);
}
/**
* 按照指定的6:9比例,对源Bitmap进行裁剪
*
* @param srcBitmap 源图片对应的Bitmap
* @return Bitmap
*/
public static Bitmap centerCrop16To9(Bitmap srcBitmap) {
int desWidth = srcBitmap.getWidth();
int desHeight = srcBitmap.getHeight();
float desRate = (float) desWidth / desHeight;
float rate = 16f / 9f;
if (desRate > rate) {//宽有多余
desWidth = (int) (desHeight * 16 / 9);
} else {//宽有不够,裁剪高度
desHeight = (int) (desWidth * 9 / 16);
}
return centerCrop(srcBitmap, desWidth, desHeight);
}
/**
* 按照指定的宽高比例,对源Bitmap进行裁剪
* 注意,输出的Bitmap只是宽高比与指定宽高比相同,大小未必相同
*
* @param srcBitmap 源图片对应的Bitmap
* @param desWidth 目标图片宽度
* @param desHeight 目标图片高度
* @return Bitmap
*/
public static Bitmap centerCrop(Bitmap srcBitmap, int desWidth, int desHeight) {
int srcWidth = srcBitmap.getWidth();
int srcHeight = srcBitmap.getHeight();
int newWidth = srcWidth;
int newHeight = srcHeight;
float srcRate = (float) srcWidth / srcHeight;
float desRate = (float) desWidth / desHeight;
int dx = 0, dy = 0;
if (srcRate == desRate) {
return srcBitmap;
} else if (srcRate > desRate) {
newWidth = (int) (srcHeight * desRate);
dx = (srcWidth - newWidth) / 2;
} else {
newHeight = (int) (srcWidth / desRate);
dy = (srcHeight - newHeight) / 2;
}
//创建目标Bitmap,并用选取的区域来绘制
Bitmap desBitmap = Bitmap.createBitmap(srcBitmap, dx, dy, newWidth, newHeight);
return desBitmap;
}
Android Bitmap 按宽高比例居中裁剪图片大小
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
相关阅读更多精彩内容
- 今天第一次正视这个bitmap.compress()方法,它用来压缩图片大小。 这个方法有三个参数: Bitmap...
- 如果图片的宽度大于父元素的宽度,不能使用margin: 0 auto;或text-align:center;来使图...