Powered By Blogger

Friday, December 6, 2013

How to change image tint color in iphone sdk?

Hi all,


This category takes an image (presumably flat and solid-colored, like a toolbar icon), and fills its non-transparent pixels with a given color. You can optionally also specify a fractional opacity at which to composite the original image over the color-filled region, to give a tinting effect.

This is very useful for generating multiple different-colored versions of the same image, for example 'disabled' or 'highlighted' states of the same basic image, without having to make multiple different-colored bitmap image files.

So, Just make two different files named as : "UIImage+Tint.h" and  "UIImage+Tint.m"


1) For  "UIImage+Tint.h" contents will be ..

#import <UIKit/UIKit.h>

@interface UIImage (ImageTint)

- (UIImage *)imageTintedWithColor:(UIColor *)color;
@end


2) For  "UIImage+Tint.m" contents will be ..
 
#import "UIImage+Tint.h"

@implementation UIImage (ImageTint)

- (UIImage *)imageTintedWithColor:(UIColor *)color
{
    if (color) {
        // Construct new image the same size as this one.
        UIImage *image;
        UIGraphicsBeginImageContextWithOptions([self size], NO, 0.0); // 0.0 for scale means "scale for device's main screen".
        CGRect rect = CGRectZero;
        rect.size = [self size];
       
        // tint the image
        [self drawInRect:rect];
        [color set];
        UIRectFillUsingBlendMode(rect, kCGBlendModeMultiply);
       
        // restore alpha channel
        [self drawInRect:rect blendMode:kCGBlendModeDestinationIn alpha:1.0f];
       
        image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
       
        return image;
    }
   
    return self;
}
@end

3) Now you can import "UIImage+Tint.h" file into your class where you want colorful images and do below code.

   UIImage *imgMail = [UIImage imageNamed:@"icon_mail.png"];
    imgMail = [imgMail imageTintedWithColor:MENU_COLOR]; //Colorful image


Important Note : Images will be preferred transparent only .

Thanks,
Nilesh M. Prajapati