Skip to content

Instantly share code, notes, and snippets.

@kreeger
Created December 16, 2012 22:25
Show Gist options
  • Save kreeger/4313707 to your computer and use it in GitHub Desktop.
Save kreeger/4313707 to your computer and use it in GitHub Desktop.
Tint an image with a particular color, using `kCGBlendModeNormal`.
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;
}
Copy link

ghost commented Mar 24, 2016

I get "Use of unresolved identifier 'kCGBlendModeNormal'" error

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment