tags:

views:

2759

answers:

4

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

[[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.

+1  A: 

-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 yout UIImageView and stting it's background colour:

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

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

Roger Nolan
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
+5  A: 

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
A: 

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.

A: 

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

Chadwick Wood