Skip to content

Instantly share code, notes, and snippets.

@taufikobet
Forked from omz/gist:1102091
Created February 20, 2018 16:17
Show Gist options
  • Save taufikobet/a5545976288d079346ecd780a9de7639 to your computer and use it in GitHub Desktop.
Save taufikobet/a5545976288d079346ecd780a9de7639 to your computer and use it in GitHub Desktop.
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment