Skip to content

Instantly share code, notes, and snippets.

Last active Dec 10, 2015
What would you like to do?
Change UIImage's color
// Heavily based on by Dan Rosenstark
// Fix for monochrome model on the comment on the same post by Ben Cunningham
// Removal of unneeded code by Daniel Ferreira (theiostream).
static UIImage *UIImageChangeColor(UIImage *image, UIColor *color_) {
CGColorRef color = [color_ CGColor];
CGRect contextRect = (CGRect){CGPointZero, [image size]};
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextBeginTransparencyLayer(ctx, NULL);
CGContextScaleCTM(ctx, 1.f, -1.f);
CGContextClipToMask(ctx, CGRectMake(contextRect.origin.x, -contextRect.origin.y, contextRect.size.width, -contextRect.size.height), [image CGImage]);
CGColorSpaceRef colorSpace = CGColorGetColorSpace(color);
CGColorSpaceModel model = CGColorSpaceGetModel(colorSpace);
const CGFloat *colors = CGColorGetComponents(color);
if (model == kCGColorSpaceModelMonochrome)
CGContextSetRGBFillColor(ctx, colors[0], colors[0], colors[0], colors[1]);
CGContextSetRGBFillColor(ctx, colors[0], colors[1], colors[2], colors[3]);
contextRect.size.height = -contextRect.size.height;
CGContextFillRect(ctx, contextRect);
UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
return img;
Copy link

drosenstark commented Dec 21, 2012

Looks great. I'll have to test it at some point, but it does look correct. Thanks!

Copy link

steipete commented Dec 22, 2012

You should use UIGraphicsBeginImageContextWithOptions, or it'll look blurry on retina devices.

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