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 *blackWithAlphaImage = [UIImage imageNamed:name];
CGSize size = blackWithAlphaImage.size;
UIGraphicsBeginImageContextWithOptions(size, YES, blackWithAlphaImage.scale);
[[UIColor whiteColor] setFill];
CGRect rect = CGRectMake(0, 0, size.width, size.height);
CGContextFillRect(UIGraphicsGetCurrentContext(), rect);
[blackWithAlphaImage drawInRect:rect];
UIImage *compositedMaskImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
CGSize unscaledSize = size;
unscaledSize.width *= blackWithAlphaImage.scale;
unscaledSize.height *= blackWithAlphaImage.scale;
UIGraphicsBeginImageContext(unscaledSize);
CGContextRef context = UIGraphicsGetCurrentContext();
[color setFill];
CGRect unscaledRect = CGRectMake(0, 0, unscaledSize.width, unscaledSize.height);
CGContextFillRect(context, unscaledRect);
UIImage *colorImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
CGImageRef compositedMaskImageRef = compositedMaskImage.CGImage;
CGImageRef mask = CGImageMaskCreate(
unscaledSize.width,
unscaledSize.height,
CGImageGetBitsPerComponent(compositedMaskImageRef),
CGImageGetBitsPerPixel(compositedMaskImageRef),
CGImageGetBytesPerRow(compositedMaskImageRef),
CGImageGetDataProvider(compositedMaskImageRef),
NULL,
false
);
CGImageRef masked = CGImageCreateWithMask([colorImage CGImage], mask);
return [UIImage imageWithCGImage:masked scale:compositedMaskImage.scale orientation:UIImageOrientationUp];
}
@end
@marcoarment

This comment has been minimized.

Copy link
Owner Author

marcoarment commented Jul 25, 2011

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.