将位图图像裁剪为自定义sguare

时间:2017-10-24 20:24:21

标签: java android image crop createbitmap

Image sample 我有这个方法用于裁剪我的图像,但是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; }

    }

1 个答案:

答案 0 :(得分: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 希望它有所帮助。