Skip to content

Instantly share code, notes, and snippets.

@kongtomorrow
Last active August 29, 2015 14:16
Show Gist options
  • Save kongtomorrow/4f6d86bea37db7124a84 to your computer and use it in GitHub Desktop.
Save kongtomorrow/4f6d86bea37db7124a84 to your computer and use it in GitHub Desktop.
templateImageByMappingWhiteToClear:
- (NSImage *)templateImageByMappingWhiteToClear:(NSImage *)image {
NSImage *output = [NSImage imageWithSize:[image size] flipped:NO drawingHandler:^BOOL(NSRect dstRect) {
CGImageRef srcCGImage = [image CGImageForProposedRect:&dstRect context:[NSGraphicsContext currentContext] hints:nil];
CGRect bounds = CGRectMake(0, 0, CGImageGetWidth(srcCGImage), CGImageGetHeight(srcCGImage));
CGContextRef maskCtx = CGBitmapContextCreate(NULL, bounds.size.width, bounds.size.height, 8, 0, CGColorSpaceCreateDeviceGray(), 0);
CGContextDrawImage(maskCtx, bounds, srcCGImage);
CGImageRef mask = CGBitmapContextCreateImage(maskCtx);
CFRelease(maskCtx);
CGContextRef ctx = [[NSGraphicsContext currentContext] graphicsPort];
CGContextDrawImage(ctx, dstRect, srcCGImage);
[[NSColor blackColor] set];
NSRectFillUsingOperation(dstRect, NSCompositeSourceAtop);
CGContextClipToMask([[NSGraphicsContext currentContext] graphicsPort], dstRect, mask);
NSRectFillUsingOperation(dstRect, NSCompositeClear);
CFRelease(mask);
return YES;
}];
[output setTemplate:YES];
return output;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment