Android PorterDuff: Why doesn't PorterDuff.Mode.SRC_IN cut out the rest of the source?

670 Views Asked by At

I'm trying to use the PorterDuff library to trim a canvas circle and rectangle to form a quarter of a square in my custom view for my app, I managed to get it to work but not fully because it trims the square out but keeps the rest of the circle in, I'm using the SRC_IN mode which seems like the right mode to use from looking at the android documentation for it but it's not working as expected, this is a snippet of the onDraw method in my custom view class:

@Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        int height = getHeight();
        int width = getWidth();
        canvas.drawCircle(width / 2, height / 2, (width + height) / 10, paint);
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        Rect rectangle = new Rect(0, 0, width / 2, height / 2);
        paint.setColor(Color.RED);
        canvas.drawRect(rectangle, paint);

    }

I'm drawing the circle in the center of the screen and then drawing the square in the top left of the screen and the PorterDuff mode should basically get the intersected part between the shapes but it just trims non-intersected square part out but doesn't do the same for the circle.

This is what it looks like: Screenshot of my app

I can't tell what i'm doing wrong here, hopefully someone can point it out.

1

There are 1 best solutions below

0
Usama Saeed US On

the issue is with the source, the rectangle is the source in this context, draw the rectangle first then use PorterDuff.Mode.SRC_IN to cut the circle based on it.

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    int height = getHeight();
    int width = getWidth();
   

    Rect rectangle = new Rect(0, 0, width / 2, height / 2);
    paint.setColor(Color.RED);
    canvas.drawRect(rectangle, paint);

    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
    canvas.drawCircle(width / 2, height / 2, (width + height) / 10, paint);

}