17

I'm attempting to add a black overlay over some current UIImage's (which are white). I've been trying to use following code:

[[UIColor blackColor] set];
[image drawAtPoint:CGPointMake(0, 0) blendMode:kCGBlendModeOverlay alpha:1.0];

But it's not working, and I'm pretty sure set isn't supposed to be there.

Oliver
  • 1,279
  • 5
  • 14
  • 20

9 Answers9

54

So, to sum up all the answers into one here's the drop-in method that works perfectly from iOS 6 all the way up to iOS 11 with all kinds of images and icons:

+ (UIImage *)filledImageFrom:(UIImage *)source withColor:(UIColor *)color{

    // begin a new image context, to draw our colored image onto with the right scale
    UIGraphicsBeginImageContextWithOptions(source.size, NO, [UIScreen mainScreen].scale);

    // get a reference to that context we created
    CGContextRef context = UIGraphicsGetCurrentContext();

    // set the fill color
    [color setFill];

    // translate/flip the graphics context (for transforming from CG* coords to UI* coords
    CGContextTranslateCTM(context, 0, source.size.height);
    CGContextScaleCTM(context, 1.0, -1.0);

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

    CGContextSetBlendMode(context, kCGBlendModeSourceIn);
    CGContextAddRect(context, rect);
    CGContextDrawPath(context,kCGPathFill);

    // generate a new UIImage from the graphics context we drew onto
    UIImage *coloredImg = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    //return the color-burned image
    return coloredImg;
}

Update: Swift 3 version

func filledImage(source: UIImage, fillColor: UIColor) -> UIImage {

    UIGraphicsBeginImageContextWithOptions(source.size, false, UIScreen.main.scale)

    let context = UIGraphicsGetCurrentContext()
    fillColor.setFill()

    context!.translateBy(x: 0, y: source.size.height)
    context!.scaleBy(x: 1.0, y: -1.0)

    context!.setBlendMode(CGBlendMode.colorBurn)
    let rect = CGRect(x: 0, y: 0, width: source.size.width, height: source.size.height)
    context!.draw(source.cgImage!, in: rect)

    context!.setBlendMode(CGBlendMode.sourceIn)
    context!.addRect(rect)
    context!.drawPath(using: CGPathDrawingMode.fill)

    let coloredImg : UIImage = UIGraphicsGetImageFromCurrentImageContext()!
    UIGraphicsEndImageContext()

    return coloredImg
}
Sergey Grischyov
  • 11,995
  • 20
  • 81
  • 120
31

You will want to clip the context to an image mask and then fill with a solid color:

- (void)drawRect:(CGRect)rect
{
    CGRect bounds = [self bounds];
    [[UIColor blackColor] set];
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextClipToMask(context, bounds, [myImage CGImage]);
    CGContextFillRect(context, bounds);
}

Note: myImage should be an instance variable that contains an UIImage. I'm not sure whether it takes the mask from the alpha channel or the intensity so try both.

rpetrich
  • 32,196
  • 6
  • 66
  • 89
  • Can you talk about where this is actually done? Am I making a subclass of UIImage? – davis Jun 23 '13 at 23:37
  • @DavisG. The above code is an example of an overridden drawRect: method in a UIView subclass. It would be very straightforward to modify it to use a bitmap context instead. – rpetrich Jun 24 '13 at 07:10
  • @rpetrich Shouldn't that be `[[UIColor blackColor] setFill]` since you're filling rather than stroking? – Daniel Rinser Jul 22 '13 at 17:10
  • @DanielRinser UIColor's set method applies the color to both the fill and the stroke. – rpetrich Jul 24 '13 at 09:35
11

I just wrote a tutorial that will help with this. My approach gives you a copy of a UIImage, with the color alterations that you want. rpetrich's approach is great, but requires that you're creating a subclass. My approach is just a few lines of code that can be dropped in wherever you need them. http://coffeeshopped.com/2010/09/iphone-how-to-dynamically-color-a-uiimage

NSString *name = @"badge.png";
UIImage *img = [UIImage imageNamed:name];

// begin a new image context, to draw our colored image onto
UIGraphicsBeginImageContext(img.size);

// get a reference to that context we created
CGContextRef context = UIGraphicsGetCurrentContext();

// set the fill color
[color setFill];

// translate/flip the graphics context (for transforming from CG* coords to UI* coords
CGContextTranslateCTM(context, 0, img.size.height);
CGContextScaleCTM(context, 1.0, -1.0);

// set the blend mode to color burn, and the original image
CGContextSetBlendMode(context, kCGBlendModeColorBurn);
CGRect rect = CGRectMake(0, 0, img.size.width, img.size.height);
CGContextDrawImage(context, rect, img.CGImage);

// set a mask that matches the shape of the image, then draw (color burn) a colored rectangle
CGContextClipToMask(context, rect, img.CGImage);
CGContextAddRect(context, rect);
CGContextDrawPath(context,kCGPathFill);

// generate a new UIImage from the graphics context we drew onto
UIImage *coloredImg = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

//return the color-burned image
return coloredImg;
Antzi
  • 12,831
  • 7
  • 48
  • 74
Chadwick Wood
  • 2,012
  • 1
  • 15
  • 9
  • 2
    If you use this method you should replace the CGContextClipToMask line with CGContextSetBlendMode(context, kCGBlendModeSourceIn); as per @seaniepie recommendation below. For me it cleared up an issue where CGContextClipToMask caused a faint outline around all images in the original color. – petrocket Nov 08 '13 at 15:50
9

Look on this method

 + (UIImage *)imageWithColor:(UIColor *)color andSize:(CGSize)size;
    {
      UIImage *img = nil;

      CGRect rect = CGRectMake(0, 0, size.width, size.height);
      UIGraphicsBeginImageContext(rect.size);
      CGContextRef context = UIGraphicsGetCurrentContext();
      CGContextSetFillColorWithColor(context,
                                     color.CGColor);
      CGContextFillRect(context, rect);
      img = UIGraphicsGetImageFromCurrentImageContext();

      UIGraphicsEndImageContext();

      return img;
    }
Voda Ion
  • 3,426
  • 2
  • 16
  • 18
9

Since iOS 7 there is a much simpler solution:

UIImage* im = [UIImage imageNamed:@"blah"];
im = [im imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
[[UIColor blackColor] setFill];
[im drawInRect:rect];
zeroimpl
  • 2,746
  • 22
  • 19
  • but when i display the result have blue color. – Shial Sep 23 '14 at 12:31
  • are you calling drawInRect yourself or just passing the image to another class? The code above only works from within a drawRect method or similar. – zeroimpl Sep 24 '14 at 13:56
  • I'm passing it to uiview. It works when i change the Uiview tintcolor for the same color as image – Shial Sep 24 '14 at 15:03
  • 1
    Yes if you are passing it to a UIKit class you will likely need to set the tintColor on the view instead of invoking the setFill method. – zeroimpl Sep 25 '14 at 17:52
3

In addition to the solution by rpetrich (which is great by the way - help me superbly), you can also replace the CGContextClipToMask line with:

    CGContextSetBlendMode(context, kCGBlendModeSourceIn); //this is the main bit!

It's the SourceIn blendmode that does the job of masking the color by whatever is in the GetCurrentContext.

  • It should be noted that one of the reasons to prefer using CGContextSetBlendMode is that with CGContextClipToMask you can get a thin outline on your image with the old color - not sure if this is a bug in the implementation or a problem with antialiasing, but using CGContextSetBlendMode fixed it for me. – petrocket Nov 08 '13 at 15:47
1

Here's how you do it with Swift 3.0 and using extensions to UIImage. Super simple.

public extension UIImage {
    func filledImage(fillColor: UIColor) -> UIImage {
        UIGraphicsBeginImageContextWithOptions(self.size, false, UIScreen.main.scale)

        let context = UIGraphicsGetCurrentContext()!
        fillColor.setFill()

        context.translateBy(x: 0, y: self.size.height)
        context.scaleBy(x: 1.0, y: -1.0)

        context.setBlendMode(CGBlendMode.colorBurn)

        let rect = CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height)
        context.draw(self.cgImage!, in: rect)

        context.setBlendMode(CGBlendMode.sourceIn)
        context.addRect(rect)
        context.drawPath(using: CGPathDrawingMode.fill)

        let coloredImg : UIImage = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()

        return coloredImg
    }
}

Then to run it simply do:

let image = UIImage(named: "image_name").filledImage(fillColor: UIColor.red)
John Riselvato
  • 12,854
  • 5
  • 62
  • 89
0

You can do that programmatically in Swift 4.x on the next way:

imageView.image = UIImage(named: "imageName")?.withRenderingMode(.alwaysTemplate)
imageView.tintColor = .purple
Hadži Lazar Pešić
  • 1,031
  • 1
  • 13
  • 20
-1

-set is used to set the colour of subsequent drawing operations which doesn't include blits. I suggest as a first call, displaying another (empty) UIView over your UIImageView and setting its background colour:

myView.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.5];

Obviously you should use the white and alpha values you want.

Community
  • 1
  • 1
Rog
  • 17,070
  • 9
  • 50
  • 73
  • 2
    The problem with this is my UIImage isn't a rectangle block, it's an icon. Wouldn't this method also draw the color around the image? Basically, I just want to convert a white UIImage to a black UIImage. – Oliver May 10 '09 at 13:28