RomanHouse RomanHouse - 1 year ago 219
iOS Question

Changing UIImage color

I'm trying to change color of UIImage. My code:

-(UIImage *)coloredImage:(UIImage *)firstImage withColor:(UIColor *)color {

CGContextRef context = UIGraphicsGetCurrentContext();
[color setFill];

CGContextTranslateCTM(context, 0, firstImage.size.height);
CGContextScaleCTM(context, 1.0, -1.0);

CGContextSetBlendMode(context, kCGBlendModeCopy);
CGRect rect = CGRectMake(0, 0, firstImage.size.width, firstImage.size.height);
CGContextDrawImage(context, rect, firstImage.CGImage);

CGContextClipToMask(context, rect, firstImage.CGImage);
CGContextAddRect(context, rect);

UIImage *coloredImg = UIGraphicsGetImageFromCurrentImageContext();

return coloredImg;

This code works, but obtained image is not so well as shoud be: bounds pixels of returned image are intermittent and not so smooth as in my first image. How can I resolve this problem?

Answer Source

THis is the most simple way of doing it.

theImageView.image = [theImageView.image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
[theImageView setTintColor:[UIColor redColor]];

In Swift 2.0+

theImageView.image? = (theImageView.image?.imageWithRenderingMode(.AlwaysTemplate))! 
theImageView.tintColor = UIColor.magentaColor()
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download