Created
July 4, 2016 09:47
-
-
Save apple-avadhesh/18dbc22680e43afbe71c6ff761600c2e to your computer and use it in GitHub Desktop.
NSImage - Image With Color Overlay
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
- (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