// 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