How to Blur effect apply on UIView in iOS?
Asked Answered
R

3

16

In my application i want to apply blur effect on uiview.So how can i achive blur effect. I tried by below code:

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];

But having problem using this code. when apply blur effect that time view became small.

Rear answered 3/9, 2015 at 2:52 Comment(1)
It looks like none of the answers addresses the question. If I'm understanding the question, the OP asks to blur the image. BlurEffectViews apply the blur to the background leaving the view alone, which is the opposite.Kanpur
B
34

Just put this blur view on the View (here yourBlurredView) which you want to be blurred. Here is an example in Objective-C:

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

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

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

and Swift:

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

visualEffectView.frame = yourBlurredView.bounds

yourBlurredView.addSubview(visualEffectView)
Brief answered 13/10, 2016 at 8:58 Comment(0)
B
7

Swift 5 Extenstion!

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)
    }
}

Use it on any subcass of UIView like this

view.applyBlurEffect(.light)
Bechuanaland answered 19/5, 2022 at 17:19 Comment(0)
S
2

If you are working with iOS 8 or later, try using a UIVisualEffectView with a UIBlurEffect.

Skin answered 3/9, 2015 at 3:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.