我有一个悬停在按钮上的图标.图标为黑色和白色,我想以编程方式“剪切”黑色区域.
如何以编程方式将图标的黑色区域转换为透明?
解决方法
您可以使用核心图像过滤器 – 特别是过滤器
CIMaskToAlpha
有关使用CIFilters的详细说明,请参见Apple’s Core Image Programming Guide和RayWenderlich tutorial
编辑:此滤镜采用黑色像素并使其完全透明,并将像素白色替换为不透明,灰色替换为部分透明等.
-(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]; }