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

前端 未结 2 403
栀梦
栀梦 2021-02-02 14:29

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

相关标签:
2条回答
  • 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];
    }
    
    0 讨论(0)
  • 2021-02-02 14:54

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

    0 讨论(0)
提交回复
热议问题