在UIImage上添加CIFilter覆盖

时间:2014-03-28 03:03:44

标签: ios sdk cifilter

我有以下代码,模糊了我的UIImage。将模糊放在UIImage之后,我还想在UIImage上放置75%不透明度的黑色屏幕,然后将这两个效果(模糊和黑屏)组合成一个UIImage。

提前谢谢!

CIFilter *gaussianBlurFilter = [CIFilter filterWithName:@"CIGaussianBlur"];
                        [gaussianBlurFilter setDefaults];
                        [gaussianBlurFilter setValue:[CIImage imageWithCGImage:[bgPicture CGImage]] forKey:kCIInputImageKey];
                        [gaussianBlurFilter setValue:@0.7 forKey:kCIInputRadiusKey];
                        CIImage *outputImage = [gaussianBlurFilter outputImage];
                        CIContext *context  = [CIContext contextWithOptions:nil];
                        CGRect rect = [outputImage extent];
                        rect.origin.x   += (rect.size.width - bgPicture.size.width ) / 2;
                        rect.origin.y   += (rect.size.height - bgPicture.size.height) / 2;
                        rect.size   = bgPicture.size;

                        CGImageRef cgimg    = [context createCGImage:outputImage fromRect:rect];
                        UIImage *image  = [UIImage imageWithCGImage:cgimg];
                        CGImageRelease(cgimg);
                        _profilePhotos[username] = image;

试过这个(不知道我插入UIColor的值是多少):

CIImage* filterInputImage = [CIImage imageWithCGImage:image.CGImage];

                        CIFilter* filter = [CIFilter filterWithName:@"CIConstantColorGenerator"];
                        [filter setValue:[UIColor colorWithRed:0/255.0 green:0/255.0 blue:0/255.0 alpha:.75] forKey:kCIInputColorKey];
                        [filter setValue:filterInputImage forKey:kCIInputImageKey];

                        CIImage* filterOutputImage = filter.outputImage;

                        CIContext* ctx = [CIContext contextWithOptions:nil];
                        CGImageRef createdImage = [ctx createCGImage:filterOutputImage fromRect:filterOutputImage.extent];

                        UIImage* outputImages = [UIImage imageWithCGImage:createdImage];

                        _profilePhotos[username] = outputImages;

1 个答案:

答案 0 :(得分:0)

Apple发布了一个关于UIImage的类别,它就是这样做的,它用一行代码完成:

UIImage *newImage = [image applyBlurWithRadius:0.7 tintColor:[UIColor colorWithRed:0/255.0 green:0/255.0 blue:0/255.0 alpha:.75] saturationDeltaFactor:0.0 maskImage:nil];

甚至还有一种辅助方法可以添加深色调:

- (UIImage *)applyDarkEffect;

和一个采用浅色并将其置于60%的颜色:

- (UIImage *)applyTintEffectWithColor:(UIColor *)tintColor;

它在github上:https://github.com/codefellows/sea-b4-ios/tree/master/UIImageEffects