Skip to content

Instantly share code, notes, and snippets.

Created May 14, 2012
What would you like to do?
CGContextClipToDrawing is a CGContext function for clipping with drawing in a block.
- (void)drawRect:(CGRect)drawRect
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextClipToDrawing(context, self.bounds, ^(CGContextRef maskContext, CGRect rect){
[[UIColor whiteColor] setFill];
CGContextFillRect(maskContext, rect);
[[UIColor blackColor] setFill];
[@"Clear" drawInRect:rect withFont:[UIFont boldSystemFontOfSize:20.0]];
[[UIColor greenColor] setFill];
CGContextFillRect(context, self.bounds);
//white gets drawn and black does not with gray being semi transparent
void CGContextClipToDrawing(CGContextRef context, CGRect rect, void(^maskDrawing)(CGContextRef maskContext, CGRect rect))
//the block draws into a context that is rendered to a grayscale CGImage which is then used to mask the calling context
CGColorSpaceRef colorspace = CGColorSpaceCreateDeviceGray();
//the mask context needs to be adjusted for scale, especially when considering retina screens
CGAffineTransform transform = CGContextGetCTM(context);
CGSize maskSize = CGSizeApplyAffineTransform(rect.size, transform);
maskSize.height = fabs(maskSize.height);
maskSize.width = fabs(maskSize.width);
CGContextRef maskContext = CGBitmapContextCreate(NULL, maskSize.width, maskSize.height, 8, maskSize.width, colorspace, 0);
//we want to ignore other transforms becasue they will be applied automatically
CGContextScaleCTM(maskContext, maskSize.width / rect.size.width, maskSize.height / rect.size.height);
maskDrawing(maskContext, CGRectMake(0.0, 0.0, rect.size.width, rect.size.height));
CGImageRef alphaMask = CGBitmapContextCreateImage(maskContext);
CGContextClipToMask(context, rect, alphaMask);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment