CGContextClip () using an inverted path

I want to crop the picture on my CGContext , but I need it just the opposite, that is, I want to add some rectangles to my clipping path using CGContextAddRect() , and clipping should be done so that all the rectangles that I added to my clipping path, not affected by any drawing operations. As a rule, this is just the opposite, i.e. The drawing functions draw rectangles that have been added to the clipping path and leave areas that have not been added to the clipping path unaffected. Therefore, I assume that I only need a way to change the clipping path before calling CGContextClip() . In QuickDraw days, this can be easily done using regions, and then calling XorRgn() for each rectangle. But with quartz it looks more complicated. Does anyone have a simple solution to achieve this, or do I need to do all these reverse path calculations myself?

+6
source share
2 answers

You can add all the borders as a rectangle, and then add the rectangles you want to exclude from drawing, and use CGContextEOClip .

Example:

 - (void)drawRect:(NSRect)dirtyRect CGContextRef ctx = [[NSGraphicsContext currentContext] graphicsPort]; //Fill the background with gray: CGContextSetRGBFillColor(ctx, 0.5, 0.5, 0.5, 1); CGContextFillRect(ctx, NSRectToCGRect(self.bounds)); CGContextAddRect(ctx, NSRectToCGRect(self.bounds)); //Add some rectangles: CGContextAddRect(ctx, CGRectMake(10, 10, 100, 100)); CGContextAddRect(ctx, CGRectMake(120, 120, 50, 100)); //Clip: CGContextEOClip(ctx); //Fill the entire bounds with red: CGContextSetRGBFillColor(ctx, 1.0, 0.0, 0.0, 1.0); CGContextFillRect(ctx, NSRectToCGRect(self.bounds)); } 

The effect becomes more apparent if you draw an image at the end instead of filling a red rectangle.

+7
source

One way is to draw a clipping path in the context of the bitmap, invert the resulting bitmap and use it as a mask on the original image by calling CGContextClipToMask() .

+2
source

Source: https://habr.com/ru/post/916000/


All Articles