/**
* 按正方形剪裁图片
* 指定正方形边长
*/
public static Bitmap imageCrop(Bitmap bitmap, int width) {
// 得到图片的宽,高
int w = bitmap.getWidth();
int h = bitmap.getHeight();
//width最大不能超过长方形的短边
if (w < width || h < width) {
width = w > h ? h : w;
}
int retX = (w - width) / 2;
int retY = (h - width) / 2;
return Bitmap.createBitmap(bitmap, retX, retY, width, width, null, false);
}
/**
* 按正方形剪裁图片
* 截最大的正方形
*/
public static Bitmap imageCrop(Bitmap bitmap) {
// 得到图片的宽,高
int w = bitmap.getWidth();
int h = bitmap.getHeight();
int width = w > h ? h : w;
int retX = (w - width) / 2;
int retY = (h - width) / 2;
return Bitmap.createBitmap(bitmap, retX, retY, width, width, null, false);
}
这两种方法截出来的正方形和原图片的中心都是重合的。其实只要善用Bitmap.createBitmap(Bitmap source, int x, int y, int width, int height)这个方法,想截什么样的图都可以。