繁体   English   中英

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

[英]How to Blur effect apply on UIView in iOS?

在我的应用程序中,我想在 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];

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

只需将此模糊视图放在要模糊的视图(此处为 yourBlurredView)上。 下面是 Objective-C 中的一个例子:

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

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

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

和斯威夫特:

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

visualEffectView.frame = yourBlurredView.bounds

yourBlurredView.addSubview(visualEffectView)

如果您使用的是 iOS 8 或更高版本,请尝试将UIVisualEffectViewUIBlurEffect一起使用。

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM