您可以将整个边界添加为矩形,然后添加要从绘图中排除的矩形并使用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));
}
如果在最后绘制图像而不是填充红色矩形,效果会变得更加明显。