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);
Nathaniel Waisbrot
  • 23,261
  • 7
  • 71
  • 99
livingtech
  • 3,570
  • 29
  • 42
  • 1
    What happens if you clip BEFORE you fill? A clip affects only the drawing that you do afterwards. – Kurt Revis Jan 06 '13 at 05:58
  • Same effect. Just a big box of the fill color. – livingtech Jan 06 '13 at 06: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: http://stackoverflow.com/a/8351807/18961 – livingtech Jan 06 '13 at 06:24

1 Answers1

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);
livingtech
  • 3,570
  • 29
  • 42