如何在 iOS 中更改部分透明图像的颜色?
我有一个具有部分透明度的单色图像。我有正常版本和@2X 版本的图像。我希望能够用代码将图像着色为不同的颜色。下面的代码适用于普通图像,但 @2X 最终会出现伪影。正常图像可能有类似的问题如果是这样,由于分辨率的原因我无法检测到它。
+(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 图像。
更新:上面的代码有效。我看到的伪像是由图像使用者进行的额外转换造成的。这个问题可以被删除,因为它不再是一个真正的问题,或者留给后代了。
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;
}
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我已经更新了上面的代码以考虑视网膜分辨率图像:
I have updated the code above to account for retina resolution images:
问题中的代码是工作代码。错误在其他地方。
The code in the question is working code. The bug was elsewhere.