Quartz2D: How to convert a clipping rectangle to an inverted mask at runtime?

Given:

  • CGContextRef ( ctx ) with frame {0,0,100,100}
  • and rect ( r ), with the frame {25,25,50,50}

It’s easy to copy context into this rectangle:

 CGContextClipToRect(ctx, r); 

To mask the red area below (red mask):

enter image description here

But I want to invert this cropping rectangle to convert it to a clipping mask . The desired result is to mask the red part below (red mask):

enter image description here

I want to do this programmatically at runtime.

I do not want to manually prepare the bitmap for sending statically with my application.

Given ctx and r , how can this be done at runtime most easily or directly?

+4
source share
3 answers

Review the fill rules in the Path Fill section of the Quartz 2D Programming Guide .

In your case, the easiest way is to use the even rosary rule. Create a path consisting of a small rectangle and a much larger rectangle:

 CGContextBeginPath(ctx); CGContextAddRect(ctx, CGRectMake(25,25,50,50)); CGContextAddRect(ctx, CGRectInfinite); 

Then cross this path into the clipping path using the even parity rule:

 CGContextEOClip(ctx); 
+14
source

You can crop the context with CGContextClipToRects() by specifying the rectangles that make up the red frame that you wanted.

+3
source

Can you just do your whole picture as usual, and then do:

 CGContextClearRect(ctx, r); 

after everything is done?

+1
source

All Articles