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

孤者浪人 提交于 2020-01-16 19:48:29

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!