如何在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图像。

更新 :上面的代码工作。 我看到的文物是由图像的消费者进行额外的转换造成的。 这个问题可以删除,因为这不是一个真正的问题,或留给子孙后代。

我更新了上面的代码来解释视网膜分辨率图像:

 - (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]; } 

问题中的代码是工作代码。 错误在别处。