Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I change a partially transparent image's color in iOS?

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.

like image 813
Brandon DuRette Avatar asked Mar 24 '11 17:03

Brandon DuRette


2 Answers

I have 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];
}
like image 159
user3130654 Avatar answered Sep 25 '22 18:09

user3130654


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

like image 4
Brandon DuRette Avatar answered Sep 24 '22 18:09

Brandon DuRette