如何将模糊应用到UIView?

现在我正在构build一个需要模糊整个UIView的iPhone应用程序。 我怎样才能做到这一点? 我已经看到了这个框架 ,但我不认为这适用于UIView。 有一种替代方法来模糊UIView?

更新 :检查下面我的更新的答案,增加与iOS 7和iOS 8的出现更多的相关性。

这应该工作。 我在代码中注释,以帮助您了解发生了什么事情:

//To take advantage of CIFilters, you have to import the Core Image framework #import <CoreImage/CoreImage.h> //Get a UIImage from the UIView UIGraphicsBeginImageContext(myView.bounds.size); [myView.layer renderInContext:UIGraphicsGetCurrentContext()]; UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); //Blur the UIImage with a CIFilter CIImage *imageToBlur = [CIImage imageWithCGImage:viewImage.CGImage]; CIFilter *gaussianBlurFilter = [CIFilter filterWithName: @"CIGaussianBlur"]; [gaussianBlurFilter setValue:imageToBlur forKey: @"inputImage"]; [gaussianBlurFilter setValue:[NSNumber numberWithFloat: 10] forKey: @"inputRadius"]; CIImage *resultImage = [gaussianBlurFilter valueForKey: @"outputImage"]; UIImage *endImage = [[UIImage alloc] initWithCIImage:resultImage]; //Place the UIImage in a UIImageView UIImageView *newView = [[UIImageView alloc] initWithFrame:self.view.bounds]; newView.image = endImage; [self.view addSubview:newView]; 

如果您对代码有任何疑问,请将其留在评论中。

注意: CIGaussianBlur在5.1版本的iOS上不存在,所以你必须find一种不同的方式来模糊设备5.x +的视图(感谢@BradLarson的这个提示)。 在这个问题上接受的答案看起来很有希望作为替代, 这个库也是如此 。

自从iOS 7发布以来,这个问题已经得到了很多点击,我想我应该跟进我最终做的事情。

我个人用photoshop模糊了这个图片,但是有许多很棒的第三方库可以做dynamic静态的模糊处理,这里有一些:

  • 这个巧妙的库从UITabBar取得一层,并适用于任何视图,以获得iOS 7的本地模糊: https : //github.com/JagCesar/iOS-blur/
  • 这个库是一个实时模糊图书馆,它模糊了下面的任何视图: https : //github.com/alexdrone/ios-realtimeblur (正如qegal所指出的)
  • 另一个做相同的实时模糊: https : //github.com/nicklockwood/FXBlurView
  • 这个图书馆是我个人使用的,是伟大的 ,允许你设置其他设置色调的颜色: https : //github.com/ivoleko/ILTranslucentView

我想发布这个,因为你不再需要截取个别框架或屏幕的截图。

iOS 8:随着即将发布的iOS 8,苹果已经包含了一个模糊的UIViewUIVisualEffectViewhttps://developer.apple.com/documentation/uikit/uivisualeffectview

在iOS 8中,您可以使用UIVisualEffectView来获取模糊的视图。 请参阅: https : //developer.apple.com/documentation/uikit/uivisualeffectview

只需解决使用此代码。

 UIToolbar *toolBar = [[UIToolbar alloc]initWithFrame:yourView.bounds]; toolBar.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight; if ([[[UIDevice currentDevice] systemVersion] doubleValue] >= 7.0) { toolBar.barTintColor = nil; toolBar.translucent = YES; toolBar.barStyle = UIBarStyleBlack; } else [toolBar setTintColor:[UIColor colorWithRed:5 green:31 blue:75 alpha:1]]; [yourView insertSubview:toolBar atIndex:0]; 

模糊视图最简单的方法是添加UIToolbar,只需更改alpha值以更改模糊。

 self.toolbar = [[UIToolbar alloc]initForAutoLayout]; [self.view addSubview:self.toolbar]; [self.toolbar autoPinEdgeToSuperviewEdge:ALEdgeLeft withInset:0]; [self.toolbar autoPinEdgeToSuperviewEdge:ALEdgeRight withInset:0]; [self.toolbar autoPinEdgeToSuperviewEdge:ALEdgeTop withInset:NAVBAR_HEIGHT]; [self.toolbar autoPinEdgeToSuperviewEdge:ALEdgeBottom withInset:0]; self.toolbar.alpha = 0.5;