Skip to content

Instantly share code, notes, and snippets.

@theiostream
Last active December 10, 2015 00:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save theiostream/4353039 to your computer and use it in GitHub Desktop.
Save theiostream/4353039 to your computer and use it in GitHub Desktop.
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

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

@steipete
Copy link

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