Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS UIImage how to convert black to transparent programmatically? [closed]

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

like image 531
Alex Stone Avatar asked Jan 07 '14 02:01

Alex Stone


2 Answers

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];
}
like image 197
foundry Avatar answered Oct 25 '22 11:10

foundry


The image would be transparent square of size of original image and the complete black region should be masked with white. When we overlay this masked image on top of the actual square image, the output would be a expected image.

Once you are ready with mask image, implement functionality of masking image.

//Masking the Thumnail Image

+(UIImage*) maskImage:(UIImage *)thumbImage withMask:(UIImage *)maskImage 
{

    CGImageRef maskRef = maskImage.CGImage;

    CGImageRef mask = CGImageMaskCreate(CGImageGetWidth(maskRef),
                                        CGImageGetHeight(maskRef),
                                        CGImageGetBitsPerComponent(maskRef),
                                        CGImageGetBitsPerPixel(maskRef),
                                        CGImageGetBytesPerRow(maskRef),
                                        CGImageGetDataProvider(maskRef), NULL, false);

    CGImageRef masked = CGImageCreateWithMask([thumbImage CGImage], mask);
    CGImageRelease(mask);
    UIImage *maskedImage = [UIImage imageWithCGImage:masked];
    CGImageRelease(masked);
    return maskedImage;

}
like image 32
Madhu Avatar answered Oct 25 '22 11:10

Madhu