Home » Ios » How to fade a UIVisualEffectView and/or UIBlurEffect in and out?

How to fade a UIVisualEffectView and/or UIBlurEffect in and out?

Posted by: admin November 30, 2017 Leave a comment

Questions:

I want to fade a UIVisualEffectsView with a UIBlurEffect in and out:

var blurEffect = UIBlurEffect(style: UIBlurEffectStyle.Dark)
var blurEffectView = UIVisualEffectView()
blurEffectView = UIVisualEffectView(effect: blurEffect)

I use a normal animation within a function called by a UIButton to fade it in, same for fading out but .alpha = 0 & hidden = true:

UIView.animateWithDuration(1, delay:0, options: .CurveEaseOut, animations: {
    self.blurEffectView.alpha = 1
}, completion: { finished in
    self.blurEffectView.hidden = false
})

Now, fading in both directions does work but it gives me an error when fading out:
<UIVisualEffectView 0x7fdf5bcb6e80> is being asked to animate its opacity. This will cause the effect to appear broken until opacity returns to 1.

Question

How do I successfully fade the UIVisualEffectsView in and out without breaking it and having a fading transition?

Note

  • I tried to put the UIVisualEffectView into a UIView and fade that one, no success
Answers:

I think this is new in iOS9, but you can now set the effect of a UIVisualEffectView inside an animation block:

let overlay = UIVisualEffectView()
// Put it somewhere, give it a frame...
UIView.animate(withDuration: 0.5) {
    overlay.effect = UIBlurEffect(style: .light)
}

Set it to nil to remove.

Questions:
Answers:

The Apple documentation (currently) states…

When using the UIVisualEffectView class, avoid alpha values that are less than 1.

and

Setting the alpha to less than 1 on the visual effect view or any of its superviews causes many effects to look incorrect or not show up at all.

I believe some important context is missing here…

I’d suggest that the intent is to avoid alpha values that are less than 1 for a persistent view. In my humble opinion this does not apply to the animation of a view.

My point – I’d suggest that alpha values less than 1 are acceptable for animations.

The terminal message states:

UIVisualEffectView is being asked to animate its opacity. This will cause the effect to appear broken until opacity returns to 1.

Reading this carefully, the effect will appear to be broken. I make two points on this:

  • the apparent break only really matters for a view that is persistent – not changing;
  • a persistent / unchanging UIVisualEffect view with an alpha value less than 1 will not present as intended / designed by Apple; and
  • the message in the terminal is not an error, just a warning.

To extend @jrturton’s answer above that helped me solve my problem, I’d add…

To fade out the UIVisualEffect use the following:

UIView.animateWithDuration(1.0, animations: {
//  EITHER...
    self.blurEffectView.effect = UIBlurEffect(nil)
//  OR...
    self.blurEffectView.alpha = 0
}, completion: { (finished: Bool) -> Void in
    self.blurEffectView.removeFromSuperview()
} )

I successfully use both methods: setting the effect property to nil and setting the alpha property to 0.

Note that setting the effect to nil creates a “nice flash” (for want of a better description) at the end of the animation, while setting the alpha to 0 creates a smooth transition.

(Let me know any syntax errors… I write in obj-c.)

Questions:
Answers:

Just a workaround – put UIVisualEffectView into a container view and change alpha property for that container. That approach works perfectly for me on iOS 9. Seems it no longer works in iOS 10.

Questions:
Answers:

Here is the solution that I ended up which works on both iOS10 and earlier versions using Swift 3

extension UIVisualEffectView {

    func fadeInEffect(_ style:UIBlurEffectStyle = .light, withDuration duration: TimeInterval = 1.0) {
        if #available(iOS 10.0, *) {
            let animator = UIViewPropertyAnimator(duration: duration, curve: .easeIn) {
                self.effect = UIBlurEffect(style: style)
            }

            animator.startAnimation()
        }else {
            // Fallback on earlier versions
            UIView.animate(withDuration: duration) {
                self.effect = UIBlurEffect(style: style)
            }
        }
    }

    func fadeOutEffect(withDuration duration: TimeInterval = 1.0) {
        if #available(iOS 10.0, *) {
            let animator = UIViewPropertyAnimator(duration: duration, curve: .linear) {
                self.effect = nil
            }

            animator.startAnimation()
            animator.fractionComplete = 1
        }else {
            // Fallback on earlier versions
            UIView.animate(withDuration: duration) {
                self.effect = nil
            }
        }
    }

}

You can also check this gist to find an example usage.

Questions:
Answers:

You can take a snapshot of a static underlying view, and fade it in and out without touching the opacity of the blur view. Assuming an ivar of blurView:

func addBlur() {
    guard let blurEffectView = blurEffectView else { return }

    //snapShot = UIScreen.mainScreen().snapshotViewAfterScreenUpdates(false)
    let snapShot = self.view.snapshotViewAfterScreenUpdates(false)
    view.addSubview(blurEffectView)
    view.addSubview(snapShot)

    UIView.animateWithDuration(0.25, animations: {
        snapShot.alpha = 0.0
    }, completion: { (finished: Bool) -> Void in
        snapShot.removeFromSuperview()
    } )
}

func removeBlur() {
    guard let blurEffectView = blurEffectView else { return }

    let snapShot = self.view.snapshotViewAfterScreenUpdates(false)
    snapShot.alpha = 0.0
    view.addSubview(snapShot)

    UIView.animateWithDuration(0.25, animations: {
        snapShot.alpha = 1.0
    }, completion: { (finished: Bool) -> Void in
        blurEffectView.removeFromSuperview()
        snapShot.removeFromSuperview()
    } )
}

Questions:
Answers:

You can change the alpha of the visual effects view without any problems, other than the warning in the console. The view may appear as simply partially transparent, rather than blurred. But this usually isn’t a problem if you’re just changing the alpha during animation.

Your app isn’t going to crash or get rejected for this. Test it on a real device (or eight). If you’re happy with how it looks and performs, it’s fine. Apple’s just warning you that it may not look or perform as well as a visual effects view with an alpha value of 1.

Questions:
Answers:

The alpha of the UIVisualEffectView always has to be 1. I think you can achieve the effect by setting the alpha of the background color.

Source : https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIVisualEffectView/index.html

Questions:
Answers:

I make an uiview which alpha is 0 and add blurview as subview of that. So i can hide/show or rounding corners it with animation.

Questions:
Answers:

If you want to fade in you UIVisualEffectView – for ios10 use UIViewPropertyAnimator

    UIVisualEffectView *blurEffectView = [[UIVisualEffectView alloc] initWithEffect:nil];
    blurEffectView.frame = self.view.frame;
    blurEffectView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;

    UIView *blackUIView = [[UIView alloc]initWithFrame:self.view.frame];
    [bacgroundImageView addSubview:blackUIView];
    [blackUIView addSubview:blurEffectView];
    UIViewPropertyAnimator *animator  = [[UIViewPropertyAnimator alloc] initWithDuration:4.f curve:UIViewAnimationCurveLinear animations:^{
        [blurEffectView setEffect:[UIBlurEffect effectWithStyle:UIBlurEffectStyleDark]];
    }];

then you can set percent

[animator setFractionComplete:percent];

for ios9 you can use alpha component

Questions:
Answers:

I ended up with the following solution, using separate animations for the UIVisualEffectView and the contents. I used the viewWithTag() method to get a reference to the UIView inside the UIVisualEffectView.

let blurEffectView = UIVisualEffectView()
// Fade in
UIView.animateWithDuration(1) { self.blurEffectView.effect = UIBlurEffect(style: .Light) }    
UIView.animateWithDuration(1) { self.blurEffectView.viewWithTag(1)?.alpha = 1 }
// Fade out
UIView.animateWithDuration(1) { self.blurEffectView.effect = nil }    
UIView.animateWithDuration(1) { self.blurEffectView.viewWithTag(1)?.alpha = 0 }

I would prefer the single animation changing the alpha, but this avoids the error and seems to work just as well.

Questions:
Answers:

I just had this problem and the way I got around it was to house the UIVisualEffectsView in a UIView, and animate that UIView’s alpha.

This worked well, except that it as soon as the alpha changed below 1.0 it turned to a solid white and looked very jarring. In order to get around this, you must set the UIView’s layer property containerView.layer.allowsGroupOpacity = false and this will prevent it from flashing white.

Now you can animate in/fade out the UIView containing the visual effects view and any other subviews using it’s alpha property and not have to worry about any graphical glitches or it logging a warning message.

Questions:
Answers:
_visualEffectView.contentView.alpha = 0;

To change the alpha of UIVisualEffectView, you should change the contentView of _visualEffectView.If you change alpha of _visualEffectView, you will get this

<UIVisualEffectView 0x7ff7bb54b490> is being asked to animate its opacity. This will cause the effect to appear broken until opacity returns to 1.

Questions:
Answers:

Usually, I only want to animate a blur when I’m presenting a view controller over the screen and want to blur the presenting view controller. Here’s an extension that adds blur() and unblur() to a view controller in order to facilitate that:

extension UIViewController {

   func blur() {
       //   Blur out the current view
       let blurView = UIVisualEffectView(frame: self.view.frame)
       self.view.addSubview(blurView)
       UIView.animate(withDuration:0.25) {
           blurView.effect = UIBlurEffect(style: .light)
       }
   }

   func unblur() {
       for childView in view.subviews {
           guard let effectView = childView as? UIVisualEffectView else { continue }
           UIView.animate(withDuration: 0.25, animations: {
                effectView.effect = nil
           }) {
               didFinish in
               effectView.removeFromSuperview()
           }
       }
   }
}

You can of course make this more robust by letting the user choose the effect style, modify the duration, call something when the animation is completed, tag the added visual effect view in blur() to ensure it’s the only one removed when you unblur(), etc., but I haven’t found the need to do these things so far, since this tends to be a “fire and forget” type of operation.