Home > database >  I am not able to achieve the blur effect in swift
I am not able to achieve the blur effect in swift

Time:02-11

I am not able to achieve the appropriate blur effect as per design in swift.

My code to add blur effect -

func addBlur() {
    let blurEffect = UIBlurEffect(style: .regular)
    let blurredEffectView = UIVisualEffectView(effect: blurEffect)
    blurredEffectView.alpha = 0.75
    imgView.alpha = 0.75
    blurredEffectView.frame = imgView.bounds
    imgView.subviews.forEach {
        $0.removeFromSuperview()
    }
    imgView.addSubview(blurredEffectView)
    imgView.bringSubviewToFront(blurredEffectView)
}

Code to remove blur effect. -

func removeBlur() {
    for subview in imgView.subviews {
        if subview is UIVisualEffectView {
            imgView.alpha = 1
            subview.removeFromSuperview()
        }
    }
}

Below is the design -

Desin blur effect

The one I achieve by my code -

Achieved screenshot

CodePudding user response:

Apple does not recommend to change the alpha property of a UIVisualEffectView and is probably why you are not seeing the blur.

Setting the Correct Alpha Value

When using the UIVisualEffectView class, avoid alpha values that are less than 1. Creating views that are partially transparent causes the system to combine the view and all the associated subviews during an offscreen render pass. UIVisualEffectView objects need to be combined as part of the content they are layered on top of in order to look correct. Setting the alpha to less than 1 on the visual effect view or any of its superviews causes many effects to

So remove this line blurredEffectView.alpha = 0.75

If you want to change the density / brightness of the blur, experiment with different styles UIBlurEffect has to offer and use the one that comes closest to your needs.

Update

If you do not get the desired results from UIVisualEffectView, you might look at CIFilter which might give you more options with more control on the properties.

Here is an example of CIFilter's gaussian blur and if you scroll down you can see some other options

CodePudding user response:

@shawn-frank is right and I want to share one cool article about blur.

Different ways to creat blur

Can not comment that why added answer

  • Related