将图像裁剪为正方形-Android [英] Crop image to square - Android
问题描述
如何从左右切割矩形图像(600 x 300)以适合正方形ImageView?我不想调整图像大小,只想将其裁剪为300 x 300.
How can I cut rectangular image (600 x 300) from left and right to fit in square ImageView ? I don't want to resize image, I just want to crop it, to be 300 x 300.
[解决方案]
如@blackbelt所说
As @blackbelt said
Bitmap cropImg = Bitmap.createBitmap(src, startX, startY, dstWidth, dstHeight);
非常适合裁剪图像.因此,如何自动裁剪具有不同尺寸的图像.我为此创建了以下简单代码:
is great for cropping images. So how can you automatically crop images with different sizes. I create this simple code for that:
// 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);
推荐答案
您可以使用
Bitmap dst = Bitmap.createBitmap(src, startX, startY, dstWidth, dstHeight);
来自文档:
从源的指定子集中返回一个不变的位图 位图.新的位图可能与源是同一对象,或者可能是副本 已制成.初始化的密度与 原始位图.
Returns an immutable bitmap from the specified subset of the source bitmap. The new bitmap may be the same object as source, or a copy may have been made. It is initialized with the same density as the original bitmap.
此处,您可以找到文档
这篇关于将图像裁剪为正方形-Android的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!