我如何在Android中自定义裁剪图像?

时间:2015-09-01 18:36:03

标签: android image android-activity canvas crop

我有一个显示图像的活动,我能够缩放图像并移动它,我在屏幕的中心有一个矩形,它不会移动,我希望它在这个矩形内的所有内容都能够裁剪图像,我该怎么做?

我有一个仅用于矩形绘制的自定义类 这是我的代码:

@Override
    public void onDraw(Canvas canvas) {
        super.onDraw(canvas);
Rect mCropRectangle = new Rect();
        mCropRectangle.set(
                getLeft(),
                getTop()+(getBottom()+getTop())/6,
                getRight(),
                getBottom()-(getBottom()+getTop())/6
                );
}

1 个答案:

答案 0 :(得分:0)

你应该可以使用PorterDuff来实现这一目标。我已经粘贴了一个使用蓝色面具裁剪大黄色背景的示例。

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        //create a second canvas
        Bitmap mask = Bitmap.createBitmap(canvas.getWidth(), canvas.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas c = new Canvas(mask);

        Rect cropRect = new Rect(100, 100, 400, 400);

        Paint p = new Paint();
        p.setAntiAlias(true);
        p.setColor(Color.BLUE); //color doesn't matter
        c.drawRect(cropRect, p); //draw the crop rect first

        p.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN)); //change transfer mode

        p.setColor(Color.YELLOW);//draw your original image/content here, pretty much whatever you wanted to draw
        c.drawRect(0, 0, getWidth(), getHeight(), p); 

        canvas.drawBitmap(mask, 0, 0, null); //draw the result back onto the canvas

    }