Android:自下而上裁剪图像

时间:2018-05-01 22:11:45

标签: java android bitmap

我有一张图片,我正在尝试将图片的裁剪版本覆盖在原始图片上。像这样:

Original Image

叠加图片 enter image description here

将叠印图像裁剪为大约50%后的图像 enter image description here

现在,我的代码会反转我想要的内容,并返回如下图像:

enter image description here

public void setOverlay(ImageView image, Bitmap originalBitmap, double percentageCompleted) {
        int percentHeight;
        int height = originalBitmap.getHeight();
        Bitmap cropped;
        if(percentageCompleted == 0){
            cropped = Bitmap.createBitmap(overlay, 0, 0, overlay.getWidth() , 0 );
        } else {
            percentHeight = (int) Math.floor(height *  (percentageCompleted));
            Log.d("HEIGHT", Double.toString(height));
            Log.d("PERCENT Completed", Double.toString(percentageCompleted));
            Log.d("PERCENT HEIGHT", Integer.toString(percentHeight));
            cropped = Bitmap.createBitmap(overlay, 0, 0, overlay.getWidth() , height-percentHeight);
        }

        originalBitmap = overlay(originalBitmap, cropped);

        //set imageview to new bitmap
        image.setImageBitmap(originalBitmap );
    }

    public Bitmap overlay(Bitmap bmp1, Bitmap bmp2) {
        Bitmap bmp3 = bmp1.copy(Bitmap.Config.ARGB_8888,true);//mutable copy
        Canvas canvas = new Canvas(bmp3 );
        canvas.drawBitmap(bmp2, new Matrix(), null);
        return bmp3;
    }

我知道我可以反转图像文件,但我想从原始图像开始并将叠加层向上绘制,而不是从叠加层开始,然后向下绘制原始图像。任何帮助表示赞赏!

1 个答案:

答案 0 :(得分:0)

您可以使用此方法:

Canvas.drawBitmap(Bitmap bitmap, Rect src, Rect dst, Paint paint)

以下是我的overlay方法可能符合您的需求:

public static Bitmap overlay(Bitmap base, Bitmap overlay, Float percentage) {
    Bitmap resultBitmap = Bitmap.createBitmap(base.getWidth(), base.getHeight(), Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(resultBitmap);

    Paint paint = new Paint();

    // base bitmap
    canvas.drawBitmap(base, 0F, 0F, paint);

    // overlay bitmap
    int yOffset = (int) (percentage * base.getHeight());
    Rect rect = new Rect(0, yOffset, overlay.getWidth(), overlay.getHeight());
    canvas.drawBitmap(overlay, rect, rect, paint);
    return resultBitmap;
}