如何在iOS中对UIView应用模糊效果?

16

在我的应用程序中,我想在UIView上应用模糊效果。那么我该如何实现模糊效果呢? 我尝试了下面的代码:

在我的应用程序中,我想在 UIView 上实现模糊效果。我该如何实现?我尝试了以下代码:

UIGraphicsBeginImageContext(scrollview.bounds.size);
[scrollview.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:3] forKey: @"inputRadius"];
CIImage *resultImage = [gaussianBlurFilter valueForKey: @"outputImage"];
UIImage *endImage = [[UIImage alloc] initWithCIImage:resultImage];

//Place the UIImage in a UIImageView
UIImageView *newView = [[UIImageView alloc] initWithFrame:scrollview.bounds];
newView.image = endImage;
[scrollview addSubview:newView];

但是我使用这段代码时遇到了问题。当应用模糊效果时,视图变小了。

3个回答

34

只需将这个模糊视图放在你想要模糊的视图上(例如yourBlurredView)。以下是Objective-C的示例:

UIVisualEffect *blurEffect; 
blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];

UIVisualEffectView *visualEffectView;
visualEffectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];

visualEffectView.frame = yourBlurredView.bounds; 
[yourBlurredView addSubview:visualEffectView];

还有Swift:

var visualEffectView = UIVisualEffectView(effect: UIBlurEffect(style: .light))    

visualEffectView.frame = yourBlurredView.bounds

yourBlurredView.addSubview(visualEffectView)

6

Swift 5 扩展!

extension UIView {
    func applyBlurEffect(_ style: UIBlurEffect.Style = .light) {
        let blurEffect = UIBlurEffect(style: style)
        let blurEffectView = UIVisualEffectView(effect: blurEffect)
        blurEffectView.frame = bounds
        blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        addSubview(blurEffectView)
    }
}

您可以像这样在任何UIView的子类上使用它:

view.applyBlurEffect(.light)

2

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接