如何从左侧和右侧剪切矩形图像(600 x 300)以适应方形ImageView?我不想调整图片大小,我只是想裁剪,是300×300将图像裁剪为正方形 - Android
[解决方法]
正如@blackbelt说
Bitmap cropImg = Bitmap.createBitmap(src, startX, startY, dstWidth, dstHeight);
是伟大的裁剪图像。那么如何自动裁剪不同尺寸的图像。我创建这个简单的代码为:
// From drawable
Bitmap src= BitmapFactory.decodeResource(context.getResources(), R.drawable.image);
// From URL
Bitmap src = null;
try {
String URL = "http://www.example.com/image.jpg";
InputStream in = new java.net.URL(URL).openStream();
src = BitmapFactory.decodeStream(in);
} catch (Exception e) {
e.printStackTrace();
}
int width = src.getWidth();
int height = src.getHeight();
int crop = (width - height)/2;
Bitmap cropImg = Bitmap.createBitmap(src, crop, 0, height, height);
ImageView.setImageBitmap(cropImg);
这正是我一直在寻找,获得完美的圆形图像,而不是椭圆形。但是,如果图像的高度大于宽度,则不会在中心裁剪,因为在createBitmap方法中y参数的值为0。这是如何解决的:添加这两行:'int cropH =(height - width)/ 2; \t cropH =(cropH <0)? 0:cropH;'使用cropH作为y值。 \t'位图cropImg = Bitmap.createBitmap(位图,cropW,cropH,newWidth,newHeight);' – 2015-03-14 14:12:52
不错,我看到你的观点....基本上要对宽度和高度进行相同的计算。 – 2015-04-18 20:49:22