2

I'm trying to change the color of an image at runtime. I've seen a couple answers on SO, but they all change the background color and not the foreground, which is what I am trying to do. I've based my code on another SO thread.

Here's the code I have:

@implementation UIImage (Coloring)

-(UIImage*) imageWithColorOverlay:(UIColor*)color
{
    //create context
    UIGraphicsBeginImageContextWithOptions(self.size, NO, self.scale);
    CGContextRef context = UIGraphicsGetCurrentContext();

    // drawingcode
    //bg
    CGRect rect = CGRectMake(0.0, 0.0, self.size.width, self.size.height);

    [self drawInRect:rect];

    //fg
    CGContextSetBlendMode(context, kCGBlendModeMultiply);

    CGContextSetFillColorWithColor(context, color.CGColor);
    CGContextFillRect(context, rect);

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    //end
    return image;
}

@end

This are the results thus far:

picture with three snapshots from the simulator

From left to right:

  1. No blending, just the normal asset. The gray bg is from the UIView behind the imageviews, the bg of the image is transparent.
  2. Multiply with kCGBlendModeMultiply
  3. Color burn with kCGBlendModeColorBurn

Is there an CGBlendMode that'll achieve replacing the foreground color? Also, is it possible to replace both the foreground color(white) and the shadow(black)?

Community
  • 1
  • 1
TMacGyver
  • 1,281
  • 3
  • 12
  • 27

1 Answers1

3

After messing around with the different blend options, this code did the trick. The only caveat is that the red tint is shown in the shadow, its not technically correct but its close enuf

@implementation UIImage (Coloring)

-(UIImage*) imageWithColorOverlay:(UIColor*)color
{
//create context
UIGraphicsBeginImageContextWithOptions(self.size, NO, self.scale);
CGContextRef context = UIGraphicsGetCurrentContext();

//drawingcode
//bg
CGRect rect = CGRectMake(0.0, 0.0, self.size.width, self.size.height);

[self drawInRect:rect];

//fg
CGContextSetBlendMode(context, kCGBlendModeMultiply);

CGContextSetFillColorWithColor(context, color.CGColor);
CGContextFillRect(context, rect);

//mask
[self drawInRect:rect blendMode:kCGBlendModeDestinationIn alpha:1.0];

//end
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

return image;
}
TMacGyver
  • 1,281
  • 3
  • 12
  • 27