Skip to content

Instantly share code, notes, and snippets.

@sujal
Created July 23, 2011 03:41
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 sujal/1100972 to your computer and use it in GitHub Desktop.
Save sujal/1100972 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 *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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment