Search code examples
iosobjective-ccolorsuiimagetransparency

iOS UIImage how to convert black to transparent programmatically?


I have an icon that's hovering over a button. The icon is black an white and I would like to "Cut" black regions out programmatically.

How can I convert black regions of an icon to transparent programmatically?

enter image description here


Solution

  • You can use Core Image Filters - in particular, the filter CIMaskToAlpha

    For detailed instructions on using CIFilters here is Apple's Core Image Programming Guide and a RayWenderlich tutorial

    Edit: this filter takes black pixels and makes them completely transparent, and replaces pixels white with opaque, gray with partially transparent, etc.

    -(void)setImage:(UIImage *)image_
    {
    
        UIImage *entryImage  = image_;
        CIContext *context = [CIContext contextWithOptions:nil];
    
        CIImage *image = [CIImage imageWithCGImage:[entryImage CGImage]];
        CIFilter *filter = [CIFilter filterWithName:@"CIMaskToAlpha"];
        [filter setDefaults];
        [filter setValue:image forKey:kCIInputImageKey];
        //    CIImage *result = [filter valueForKey:kCIOutputImageKey];
        CIImage *result = [filter outputImage];
    
        CGImageRef cgImage = [context createCGImage:result fromRect:[result extent]];
    
        UIImage *newImage = [UIImage imageWithCGImage:cgImage scale:[entryImage scale] orientation:UIImageOrientationUp];
        CGImageRelease(cgImage);
        [super setImage:newImage];
    }