0

I'm sure the answer for this exists on stackoverflow, but I've been looking and haven't been able to find it yet. Essentially, I have several images with transparent backgrounds and some black imagery, I want to be able to change the color of the black part to some other arbitrary color.

I'm relatively sure this is achievable with Quartz Image Masking, but I haven't been able to find any good examples, so that is what I'm looking for. Other solutions are also welcome.

Thanks!!!

UPDATE: I think I'm pretty close with this code... but my mask isn't working. My UIView does get filled with the fill color though, but it's just a giant rectangle, not clipped whatsoever.

UPDATE #2: I am even closer now (I think) with the following code. The problem is that my background is now black, rather than transparent.

CGContextRef context = UIGraphicsGetCurrentContext();

CGContextScaleCTM(context, 1, -1);
CGContextTranslateCTM(context, 0, -rect.size.height);

CGImageRef maskImage = [self.image CGImage];
CGContextClipToMask(context, rect, maskImage);

[_colorToChangeInto setFill];
CGContextFillRect(context, rect);
3
  • 1
    What happens if you clip BEFORE you fill? A clip affects only the drawing that you do afterwards.
    – Kurt Revis
    Jan 6, 2013 at 5:58
  • Same effect. Just a big box of the fill color.
    – livingtech
    Jan 6, 2013 at 6:17
  • Hmmm. If I get rid of the colorSpace BS and just use the image as the mask directly, I get an image that is close to what I want, but the background is black, rather than transparent. (I need to flip coordinates, which I can do via CGContextScaleCTM(mainViewContentContext, 1, -1); CGContextTranslateCTM(mainViewContentContext, 0, -rect.size.height);.) That solution courtesy of another answer here: stackoverflow.com/a/8351807/18961
    – livingtech
    Jan 6, 2013 at 6:24

1 Answer 1

1

The answer is already in the question above. It wasn't quite working because I was creating the image in IB (in a storyboard), and hadn't set the background color. Somehow that defaulted to Black. SO FRUSTRATING!!!

Anyway, after I changed the background color to transparent, the following code works like a charm!

CGContextRef context = UIGraphicsGetCurrentContext();

CGContextScaleCTM(context, 1, -1);
CGContextTranslateCTM(context, 0, -rect.size.height);

CGImageRef maskImage = [self.image CGImage];
CGContextClipToMask(context, rect, maskImage);

[_colorToChangeInto setFill];
CGContextFillRect(context, rect);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.