如何在iOS中更改部分透明图像的颜色?
我有一个具有部分透明度的单色图像。我有正常和@ 2X版本的图像。我希望能够以代码形式为图像着色另一种颜色。下面的代码适用于正常图像,但@ 2X最终会出现伪影。正常图像可能有类似的问题如果是这样,我无法通过解决方案检测到它。如何在iOS中更改部分透明图像的颜色?
+(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图像。
更新:上面的代码有效。我看到的工件是由图像消费者完成的附加转换引起的。这个问题可以被删除,因为它不再是一个真正的问题,或者留给子孙后代。
问题中的代码是工作代码。该错误是其他地方。
我已经更新上面的代码要占视网膜分辨率的图片:
- (UIImage *) changeColorForImage:(UIImage *)mask toColor:(UIColor*)color {
CGImageRef maskImage = mask.CGImage;
CGFloat width = mask.scale * mask.size.width;
CGFloat height = mask.scale * mask.size.height;
CGRect bounds = CGRectMake(0,0,width,height);
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef bitmapContext = CGBitmapContextCreate(NULL, width, height, 8, 0, colorSpace, (CGBitmapInfo)kCGImageAlphaPremultipliedLast);
CGContextClipToMask(bitmapContext, bounds, maskImage);
CGContextSetFillColorWithColor(bitmapContext, color.CGColor);
CGContextFillRect(bitmapContext, bounds);
CGImageRef mainViewContentBitmapContext = CGBitmapContextCreateImage(bitmapContext);
CGContextRelease(bitmapContext);
return [UIImage imageWithCGImage:mainViewContentBitmapContext scale:mask.scale orientation:UIImageOrientationUp];
}
适用于视网膜显示。谢谢! – Colas 2014-12-09 15:13:47
此代码不尊重内存管理的CreateRule,并且无法释放色彩空间。不要忘了'CGColorSpaceRelease(colorSpace)'以避免泄漏! – AliSoftware 2014-12-22 16:22:53
(你也应该释放'CGImageRed mainViewContentBitmapContext') – AliSoftware 2014-12-22 19:58:32
谢谢老兄你的问题解决了我的问题 – 2013-04-15 04:56:35
这段代码有漏洞(上'colorSpace',但更重要的是'mainViewContentBitmapContext',这可能在记忆中相当大)。请参阅我对以下答案的评论以获取指示。 – AliSoftware 2014-12-22 20:00:13