问题
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);
回答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);
来源:https://stackoverflow.com/questions/14176569/i-want-to-use-quartz-to-make-a-single-color-image-a-different-color