将图像裁剪为方形 - Android

KiK*_*iKo 17 android android-imageview resize-crop

如何从左右切割矩形图像(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);
Run Code Online (Sandbox Code Playgroud)

fau*_*r21 23

在上面的答案上稍微扩展一下

因为在某些情况下你可以最终得到一个异常不是预期的结果,只需使用Bitmap.createBitmap(),就像下载一样:

java.lang.IllegalArgumentException:x + width必须是<= bitmap.width()

Heres是一个小功能,可以完成裁剪并处理一些公共案例.

编辑:根据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;
}
Run Code Online (Sandbox Code Playgroud)

我用一些不同分辨率和大小的图像做了几次测试,它按预期工作.

它也可以在其他情况下使用,例如当您尝试制作"完美"的圆形图像并需要传递方形位图等时.


Gau*_*tam 6

设置固定的图像视图高度、宽度,并为图像视图设置两个属性

android:adjustViewBounds="true" 
android:scaleType="centerCrop"
Run Code Online (Sandbox Code Playgroud)

完毕


Bla*_*elt 4

您可以使用

Bitmap dst = Bitmap.createBitmap(src, startX, startY, dstWidth, dstHeight);
Run Code Online (Sandbox Code Playgroud)

从文档中:

从源位图的指定子集返回不可变位图。新位图可能是与源相同的对象,或者可能已制作了副本。它以与原始位图相同的密度进行初始化。

在这里您可以找到文档