如何在iOS中更改部分透明图像的颜色? [英] How do I change a partially transparent image's color in iOS?
问题描述
我有一个具有部分透明度的单色图像.我同时拥有普通版和@ 2X版的图片.我希望能够用代码将图像着色为其他颜色.下面的代码对于正常图像可以正常工作,但是@ 2X最终会出现伪像.普通图像可能有类似的问题.如果是这样,由于分辨率我无法检测到它.
I have a single-color image that has partial transparency. I have both normal and @2X versions of the image. I would like to be able to tint the image a different color, in code. The code below works fine for the normal image, but the @2X ends up with artifacts. The normal image might have a similar issue If so, I can't detect it on account of resolution.
+(UIImage *) newImageFromMaskImage:(UIImage *)mask inColor:(UIColor *) color {
CGImageRef maskImage = mask.CGImage;
CGFloat width = mask.size.width;
CGFloat height = mask.size.height;
CGRect bounds = CGRectMake(0,0,width,height);
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef bitmapContext = CGBitmapContextCreate(NULL, width, height, 8, 0, colorSpace, kCGImageAlphaPremultipliedLast);
CGContextClipToMask(bitmapContext, bounds, maskImage);
CGContextSetFillColorWithColor(bitmapContext, color.CGColor);
CGContextFillRect(bitmapContext, bounds);
CGImageRef mainViewContentBitmapContext = CGBitmapContextCreateImage(bitmapContext);
CGContextRelease(bitmapContext);
UIImage *result = [UIImage imageWithCGImage:mainViewContentBitmapContext];
return result;
}
如果重要,将使用UIImage imageNamed:
加载蒙版图像.另外,我确认在视网膜模拟器上运行时@ 2X图像正在加载.
If it matters, the mask image is loaded using UIImage imageNamed:
. Also, I confirmed that the @2X image is loading when run on the retina simulator.
更新:以上代码有效.我看到的工件是由图像使用者进行的其他转换引起的.该问题可以删除,因为它不再是一个真正的问题,也可以留给后代.
Update: The above code works. The artifacts I was seeing were caused by additional transforms done by the consumer of the images. This question could be deleted since it's not really a question anymore or left for posterity.
推荐答案
问题中的代码是有效代码.该错误在其他地方.
The code in the question is working code. The bug was elsewhere.
这篇关于如何在iOS中更改部分透明图像的颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!