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?
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];
}
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With