如何从左侧和右侧剪切矩形图像(600 x 300)以适合方形 ImageView ?我不想调整图像大小,我只想将其裁剪为 300 x 300。
[解决方案]
正如@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);
对上面的答案进行一些扩展
因为在某些情况下你可能会得到一个例外 or 不是预期的结果,只需使用 Bitmap.createBitmap() 即可,如下所示:
java.lang.IllegalArgumentException:x + 宽度必须
这是一个小函数,可以进行裁剪并处理一些常见情况。
Edit:根据 droidster 的声明进行了相应更新。
public static Bitmap cropToSquare(Bitmap bitmap){
int width = bitmap.getWidth();
int height = bitmap.getHeight();
int newWidth = (height > width) ? width : height;
int newHeight = (height > width)? height - ( height - width) : height;
int cropW = (width - height) / 2;
cropW = (cropW < 0)? 0: cropW;
int cropH = (height - width) / 2;
cropH = (cropH < 0)? 0: cropH;
Bitmap cropImg = Bitmap.createBitmap(bitmap, cropW, cropH, newWidth, newHeight);
return cropImg;
}
我对一些不同分辨率和尺寸的图像进行了多次测试,它按预期工作。
它也可以用于其他情况,例如当您尝试制作“完美”的圆形图像并需要传递方形位图等时。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)