Skip to content

Instantly share code, notes, and snippets.

@apple-avadhesh
Created July 4, 2016 09:47
Show Gist options
  • Save apple-avadhesh/18dbc22680e43afbe71c6ff761600c2e to your computer and use it in GitHub Desktop.
Save apple-avadhesh/18dbc22680e43afbe71c6ff761600c2e to your computer and use it in GitHub Desktop.
NSImage - Image With Color Overlay
- (NSImage *)imageWithColorOverlay:(NSColor *)color {
CGFloat scale = [self recommendedLayerContentsScale:[[NSScreen mainScreen] backingScaleFactor]];
NSImage * overlayedImage = [[NSImage alloc] initWithSize:self.size];
[self.representations enumerateObjectsUsingBlock:^(NSImageRep * imageRep, NSUInteger idx, BOOL *stop){
CGFloat imageWidth = imageRep.pixelsWide ?: imageRep.size.width * scale;
CGFloat imageHeight = imageRep.pixelsHigh ?: imageRep.size.height * scale;
NSRect imageRect = NSMakeRect(0, 0, imageWidth, imageHeight);
CGImageRef imageRef = [imageRep CGImageForProposedRect:&imageRect context:NULL hints:nil];
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef context = CGBitmapContextCreate(NULL, imageWidth, imageHeight,
CGImageGetBitsPerComponent(imageRef), 0,
colorSpace, (CGBitmapInfo)kCGImageAlphaPremultipliedLast);
CGColorSpaceRelease(colorSpace);
CGContextClipToMask(context, NSRectToCGRect(imageRect), imageRef);
CGContextSetFillColorWithColor(context, color.CGColor);
CGContextFillRect(context, NSRectToCGRect(imageRect));
CGImageRef newImage = CGBitmapContextCreateImage(context);
CGContextRelease(context);
[overlayedImage addRepresentation:[[NSBitmapImageRep alloc] initWithCGImage:newImage]];
CGImageRelease(newImage);
}];
return overlayedImage;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment