如何淡入淡出 UIVisualEffectView 和/或 UIBlureffect?

我想在 UIVisualEffectsView 中加入和删除一个 UIBlureffect:

var blurEffectView = UIVisualEffectView()
blurEffectView = UIVisualEffectView(effect: UIBlurEffect(style: .dark))

我在一个由 UIButton调用的函数中使用一个普通的动画来淡入淡出,淡出也是如此,但是 .alpha = 0 & hidden = true:

blurEffectView.hidden = false
UIView.animate(withDuration: 1, delay: 0, options: .curveEaseOut) {
self.blurEffectView.alpha = 1
}

现在,在两个方向上衰落确实有效,但是在衰落 出去时会给我一个错误:

<UIVisualEffectView 0x7fdf5bcb6e80>被要求动画其不透明度。这将导致效果看起来中断,直到不透明度返回到1。

提问

我如何成功褪色的 UIVisualEffectView进出没有 崩溃它和有一个褪色过渡?

注意

  • 我试着把 UIVisualEffectView放到 UIView里然后淡化它,没有成功
49164 次浏览

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

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.

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.

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

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.

VERY IMPORTANT - When testing this on the simulator, make sure to set your simulator's Graphics Quality Override to High Quality in order for this to work.

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.

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.

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. My points on this being:

  • 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 (Objective-C) code:

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

_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.

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

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.

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.

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.

based on @cc's answer i modified his extension to blur a view

extension UIView {


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


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

Improving @Tel4tel and @cc response, here is an extension with parameters and a brief explanation.

extension UIView {


// Perform a blur animation in the whole view
// Effect tone can be .light, .dark, .regular...
func blur(duration inSeconds: Double, effect tone: UIBlurEffectStyle) {
let blurView = UIVisualEffectView(frame: self.bounds)
self.addSubview(blurView)
UIView.animate(withDuration: inSeconds) {
blurView.effect = UIBlurEffect(style: tone)
}
}


// Perform an unblur animation in the whole view
func unblur(duration inSeconds: Double) {
for childView in subviews {
guard let effectView = childView as? UIVisualEffectView else { continue
}
UIView.animate(withDuration: inSeconds, animations: {
effectView.effect = nil
}){
didFinish in effectView.removeFromSuperview()
}
}
}
}

Then you can use it like: view.blur(duration: 5.0, effect: .light) or view.unblur(duration: 3.0)

Remember to NOT use it in viewDidLoad() as it will override the animation. Also, when running on a Simulator, turn the graphics to the Higher level to be able to see the animation (Debug > Graphics Quality Override > High Quality).