Khaled
Khaled

Reputation: 86

Multiple clipping regions in canvas?

I want to clip multiple regions of an image, so I have a custom class extending ImageView

This is my onDraw:

@Override
protected void onDraw(Canvas canvas) {

        canvas.clipRect(rect1);
        canvas.clipRect(rect2);

    super.onDraw(canvas);

}

When I clip 1 rectangle it works fine, but when I have multiple it doesn't show anything at all.

UPDATE:

I also tried clipping using Path instead:

@Override
protected void onDraw(Canvas canvas) {

    canvas.clipPath(path1);
    canvas.clipPath(path2);

    super.onDraw(canvas);

}

But none works

Upvotes: 0

Views: 1675

Answers (2)

RabidMutant
RabidMutant

Reputation: 611

It will be intersecting or replaced in your rects.

Try using clipPath(...) instead.

ie.

Path p1 = ...;
Path p2 = ...;
p2.addPath(p1);
canvas.clipRect(p2);

If for some reason clipPath does not work, then build a region and use clipRegion.

Edit:

As per OPs final solution, it is also possible to merge the regions at the time of adding the clip region:

canvas.clip{whatever}(rect/region/path, op).

Upvotes: 0

Khaled
Khaled

Reputation: 86

I found the solution, which is using:

canvas.clipPath(Path path, Op op);

instead of:

canvas.clipPath(Path path);

With extra clips, and this also works with Rect and Region.

This how my code looks like:

Path path1 = new Path();

private void init(){

    path1.moveTo(100, 100);
    path1.lineTo(100, 500);
    path1.lineTo(500, 500);
    path1.lineTo(500, 100);
    path1.close();

}

@Override
protected void onDraw(Canvas canvas) {

    canvas.clipPath(path1);
    canvas.clipPath(path2, Region.Op.UNION);
    canvas.clipPath(path3, Region.Op.UNION);

    super.onDraw(canvas);

}

Upvotes: 2

Related Questions