How to change partially transparent image color in iOS?

I have a monochrome image with partial transparency. I have both regular and @ 2X versions of the image. I would like to be able to tint an image of a different color in the code. The code below works fine for a regular image, but @ 2X ends with artifacts. A regular image may have a similar problem. If so, I cannot detect it due to permission.

+(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 that matters, the mask image is loaded using UIImage imageNamed: In addition, I confirmed that the @ 2X image loads when run on the retina simulator.

Update : The above code works. The artifacts that I saw were caused by additional conversions made by the image consumer. This question could be deleted because it is no longer a question or left to posterity.

+17
ios uiimage quartz-2d retina-display
Mar 24 '11 at 17:38
source share
2 answers

The code in the question is the working code. The error was elsewhere.

+4
Apr 18 '11 at 15:43
source share

I updated the code above to account for retina resolution images:

 - (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]; } 
+9
Dec 23 '13 at 20:03
source share



All Articles