How to tint a transparent PNG image in iPhone?

Viewed 42033

I know it's possible to tint a rectangular image by drawing a CGContextFillRect over it and setting the blend mode. However, I can't figure out how to do a tint on a transparent image such as an icon. It must be possible since the SDK does it itself on tab-bars in such. Would anyone be able to provide a snippet?

UPDATE:

Lots of great suggestions have been given for this problem since I originally asked. Be sure to read through all the answers to figure out what suits you best.

UPDATE (Apr 30, 2015):

With iOS 7.0, I can now just do the following, which would satisfy the needs of my original question. But if you have more complicated cases, check out all the answers.

UIImage *iconImage = [[UIImage imageNamed:@"myImageName"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];    
UIImageView *icon = [[UIImageView alloc] initWithImage:iconImage];
icon.tintColor = [UIColor redColor];
13 Answers

I can get results very close to the tint in the Apple navigation bar by using kCGBlendModeOverlay. Taking excelent @fabb answer and combining @omz approach in this post https://stackoverflow.com/a/4684876/229019 I came with this solution that helds the results I was expecting:

- (UIImage *)tintedImageUsingColor:(UIColor *)tintColor;
{
    UIGraphicsBeginImageContextWithOptions (self.size, NO, [[UIScreen mainScreen] scale]);

    CGContextRef context = UIGraphicsGetCurrentContext();
    CGRect rect = CGRectMake(0, 0, self.size.width, self.size.height);

    // draw original image
    [self drawInRect:rect blendMode:kCGBlendModeNormal alpha:1.0f];

    // tint image (loosing alpha). 
    // kCGBlendModeOverlay is the closest I was able to match the 
    // actual process used by apple in navigation bar 
    CGContextSetBlendMode(context, kCGBlendModeOverlay);
    [tintColor setFill];
    CGContextFillRect(context, rect);

    // mask by alpha values of original image
    [self drawInRect:rect blendMode:kCGBlendModeDestinationIn alpha:1.0f];

    UIImage *tintedImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return tintedImage;
}

Here's an example tinting several grayscale images with transparency:

Rendered Example:

  • The first line is the apple toolbar tinted [UIColor orangeColor].
  • The second line is the same gradient tinted in several colors starting with clear color (= the actual gradient) and ending with the same orange.
  • The third is a simple circle with transparency (the linen is the background color)
  • The forth line is a complex dark noisy texture
Related