Last active
December 10, 2015 00:39
-
-
Save theiostream/4353039 to your computer and use it in GitHub Desktop.
Change UIImage's color
This file contains hidden or 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
// 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; | |
} |
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
Looks great. I'll have to test it at some point, but it does look correct. Thanks!