Skip to content

Instantly share code, notes, and snippets.

@theiostream
Last active Dec 10, 2015
Embed
What would you like to do?
Change UIImage's color
// Heavily based on http://compileyouidontevenknowyou.blogspot.com.br/2010/12/change-colors-of-uiimage-using-uicolor.html 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]};
UIGraphicsBeginImageContext(contextRect.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]);
else
CGContextSetRGBFillColor(ctx, colors[0], colors[1], colors[2], colors[3]);
contextRect.size.height = -contextRect.size.height;
CGContextFillRect(ctx, contextRect);
CGContextEndTransparencyLayer(ctx);
UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return img;
}
@drosenstark
Copy link

drosenstark commented Dec 21, 2012

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

@steipete
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