Skip to content

Instantly share code, notes, and snippets.

@davbeck
Created May 14, 2012 21:49
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davbeck/2697540 to your computer and use it in GitHub Desktop.
Save davbeck/2697540 to your computer and use it in GitHub Desktop.
CGContextClipToDrawing is a CGContext function for clipping with drawing in a block.
- (void)drawRect:(CGRect)drawRect
{
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSaveGState(context);
CGContextClipToDrawing(context, self.bounds, ^(CGContextRef maskContext, CGRect rect){
UIGraphicsPushContext(maskContext);
[[UIColor whiteColor] setFill];
CGContextFillRect(maskContext, rect);
[[UIColor blackColor] setFill];
[@"Clear" drawInRect:rect withFont:[UIFont boldSystemFontOfSize:20.0]];
UIGraphicsPopContext();
});
[[UIColor greenColor] setFill];
CGContextFillRect(context, self.bounds);
CGContextRestoreGState(context);
}
//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);
CGImageRelease(alphaMask);
CGContextRelease(maskContext);
CGColorSpaceRelease(colorspace);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment