Search code examples
iosobjective-ccolorstransparentmask

IOS: color only the transparent pixels


If I have an image with some transparent pixels, is there any possibility to color the transparent pixels with white and make the rest of the image transparent in objective-c?

Thanks!


Solution

  • I found a solution:

    - (UIImage*)convertToInverseWhiteMask: (UIImage *) image {
        UIGraphicsBeginImageContextWithOptions(image.size, NO, image.scale);
        CGRect imageRect = CGRectMake(0.0f, 0.0f, image.size.width, image.size.height);
        CGContextRef ctx = UIGraphicsGetCurrentContext();
    
        // Draw a white background (for white mask)
        CGContextSetRGBFillColor(ctx, 1.0f, 1.0f, 1.0f, 1.0f);
        CGContextFillRect(ctx, imageRect);
    
        // Apply the source image's alpha
        [image drawInRect:imageRect blendMode:kCGBlendModeDestinationOut alpha:1.0f];
    
        UIImage* mask = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        return mask; 
       }