0

图像示例 我编写了这种用于裁剪图像的方法,但 HEIGHT 尺寸不适用于裁剪,只有权重正确。我找不到问题。我想使用我的屏幕宽度和高度作为动态宽度和高度。

public Bitmap cropToSquare(Bitmap bitmap){
        int width  = mScreenWidth ;
        int height = mScreenHeight;
        int newWidth = width - 2 * 10;
        int newHeight = (height- newWidth) / 2;

        Bitmap cropImg = Bitmap.createBitmap(bitmap, 0, 0, newWidth, newHeight);
        return cropImg; }

    }
4

1 回答 1

0

这是我的解决方案:

public static Bitmap getResizedClippedBitmap (Bitmap bm, int newWidth, int newHeight) {

    Bitmap targetBitmap = Bitmap.createBitmap(newWidth, newHeight, Bitmap.Config.ARGB_8888);

    Canvas canvas = new Canvas(targetBitmap);

    float originalWidth = bm.getWidth();
    float originalHeight = bm.getHeight();

    float scale, xTranslation = 0.0f, yTranslation = 0.0f;
    if (originalWidth > originalHeight) {
        scale = newHeight/originalHeight;
        xTranslation = (newWidth - originalWidth * scale)/2.0f;
    }
    else {
        scale = newWidth / originalWidth;
        yTranslation = (newHeight - originalHeight * scale)/2.0f;
    }

    Matrix transformation = new Matrix();
    transformation.postTranslate(xTranslation, yTranslation);
    transformation.preScale(scale, scale);

    Paint paint = new Paint();
    paint.setFilterBitmap(true);
    canvas.drawBitmap(bm, transformation, paint);

    return targetBitmap;
}

您可以在此处找到其他一些实用程序:BitmapUtils.java 希望对您有所帮助。

于 2017-10-24T21:32:16.320 回答