Created
December 16, 2012 22:25
-
-
Save kreeger/4313707 to your computer and use it in GitHub Desktop.
Tint an image with a particular color, using `kCGBlendModeNormal`.
This file contains 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
UIImage *TintImageWithTintColor(UIImage *image, UIColor *tintColor) { | |
// Huge props to http://stackoverflow.com/questions/3514066/how-to-tint-a-transparent-png-image-in-iphone | |
UIGraphicsBeginImageContext(image.size); | |
CGContextRef context = UIGraphicsGetCurrentContext(); | |
CGContextTranslateCTM(context, 0, image.size.height); | |
CGContextScaleCTM(context, 1.0, -1.0); | |
CGRect rect = (CGRect){ CGPointZero, image.size }; | |
// image drawing code | |
// draw black background to preserve color of transparent pixels | |
CGContextSetBlendMode(context, kCGBlendModeNormal); | |
[[UIColor blackColor] setFill]; | |
CGContextFillRect(context, rect); | |
// draw original image | |
CGContextSetBlendMode(context, kCGBlendModeNormal); | |
CGContextDrawImage(context, rect, image.CGImage); | |
// tint image (loosing alpha) - the luminosity of the original image is preserved | |
CGContextSetBlendMode(context, kCGBlendModeColor); | |
[tintColor setFill]; | |
CGContextFillRect(context, rect); | |
// mask by alpha values of original image | |
CGContextSetBlendMode(context, kCGBlendModeDestinationIn); | |
CGContextDrawImage(context, rect, image.CGImage); | |
UIImage *coloredImage = UIGraphicsGetImageFromCurrentImageContext(); | |
UIGraphicsEndImageContext(); | |
return coloredImage; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I get "Use of unresolved identifier 'kCGBlendModeNormal'" error