Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Creating arbitrarily-colored icons from a black-with-alpha master image (iOS)
// Usage example:
// input image: http://f.cl.ly/items/3v0S3w2B3N0p3e0I082d/Image%202011.07.22%2011:29:25%20PM.png
//
// UIImage *buttonImage = [UIImage ipMaskedImageNamed:@"UIButtonBarAction.png" color:[UIColor redColor]];
// .h
@interface UIImage (IPImageUtils)
+ (UIImage *)ipMaskedImageNamed:(NSString *)name color:(UIColor *)color;
@end
// .m
@implementation UIImage (IPImageUtils)
+ (UIImage *)ipMaskedImageNamed:(NSString *)name color:(UIColor *)color
{
UIImage *image = [UIImage imageNamed:name];
CGRect rect = CGRectMake(0, 0, image.size.width, image.size.height);
UIGraphicsBeginImageContextWithOptions(rect.size, NO, image.scale);
CGContextRef c = UIGraphicsGetCurrentContext();
[image drawInRect:rect];
CGContextSetFillColorWithColor(c, [color CGColor]);
CGContextSetBlendMode(c, kCGBlendModeSourceAtop);
CGContextFillRect(c, rect);
UIImage *result = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return result;
}
@end
@mrjjwright

This comment has been minimized.

Copy link

mrjjwright commented Jul 26, 2011

Trying to figure out how to write this in AppKit: https://gist.github.com/1106004 but can't quite it.

@TitouanVanBelle

This comment has been minimized.

Copy link

TitouanVanBelle commented Dec 7, 2012

It's a shame it doesn't allow the image to have shadows.

@kerembirinci

This comment has been minimized.

Copy link

kerembirinci commented Feb 19, 2014

Thank you so much. It helped me a lot.

@faithfracture

This comment has been minimized.

Copy link

faithfracture commented May 12, 2014

Thanks for this!

Question: Why no call to UIGraphicsEndImageContext() before returning? I'm not real familiar with the way graphics context works, but according to the "Creating New Images" section of the apple docs (https://developer.apple.com/library/ios/documentation/2ddrawing/conceptual/drawingprintingios/HandlingImages/Images.html#//apple_ref/doc/uid/TP40010156-CH13-SW8) you're supposed to call that when you're done to pop the context you created off the graphics stack.

@joeboyscout04

This comment has been minimized.

Copy link

joeboyscout04 commented Jun 28, 2016

faithfracture is very wise. Leaving off the UIGraphicsEndImageContext() will cause a memory leak in your application. I know, because it happened to us after a developer used this code.

@VincentVToscano

This comment has been minimized.

Copy link

VincentVToscano commented Dec 9, 2016

Great gist. Has anyone updated/forked the above based on the last 2 comments?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.