如何在所有四个方面裁剪位图?

How to crop Bitmap on all four sides?

我正在尝试编写一种方法,它将 Bitmap 和裁剪值作为参数,returns 裁剪后的 Bitmap

我的代码:

public Bitmap applyCrop(Bitmap bitmap, int leftCrop, int topCrop, int rightCrop, int bottomCrop) {
    return Bitmap.createBitmap(bitmap, leftCrop, topCrop, bitmap.getWidth() - rightCrop, bitmap.getHeight() - bottomCrop);
}

使用此代码,我收到以下内容 IllegalArgumentException

java.lang.IllegalArgumentException: x + width must be <= bitmap.width()

我的代码有什么问题?

如果Bitmap.createBitmap()采用裁剪图像的大小而不是第二个角的坐标,您应该这样做:

public Bitmap applyCrop(Bitmap bitmap, int leftCrop, int topCrop, int rightCrop, int bottomCrop) {
    int cropWidth = bitmap.getWidth() - rightCrop - leftCrop;
    int cropHeight = bitmap.getHeight() - bottomCrop - topCrop;
    return Bitmap.createBitmap(bitmap, leftCrop, topCrop, cropWidth, cropHeight);
}

这里我有一个样品给你。使用这个

Bitmap bitmap=BitmapFactory.decodeResource(getResources(), R.drawable.abc);


//pass your bitmap here and give desired width and height
newBitmap=Bitmap.createBitmap(bitmap, 0,0,"GIVE WIDTH HERE", "GIVE HEIGHT HERE");

如果可行,请告诉我! :)