Created
September 1, 2011 05:48
-
-
Save sdrew/1185537 to your computer and use it in GitHub Desktop.
Revisions
-
marcoarment created this gist
Jul 23, 2011 .There are no files selected for viewing
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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,57 @@ // 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