livingtech
livingtech

Reputation: 3660

I want to use Quartz to make a single color image a different color

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);

Upvotes: 0

Views: 295

Answers (1)

livingtech
livingtech

Reputation: 3660

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);

Upvotes: 1

Related Questions