Animating UIVisualEffectView Blur Radius?
Asked Answered
B

1

13

As the title says it, is there a way to animate a UIVisualEffectView's blur radius? I have a dynamic background behind the view so the ImageEffects addition can't be used... The only thing that can do this as far as I know is to animate the opacity but iOS complains saying that doing that breaks the EffectView so it definitely seems like a bad idea... Any help would be gladly appreciated.

Barring answered 26/3, 2015 at 12:25 Comment(0)
S
11

The answer is yes. Here's an example for animating from no blur -> blur:

// When creating your view...
let blurView = UIVisualEffectView()
// Later, when you want to animate...
UIView.animateWithDuration(1.0) { () -> Void in
    blurView.effect = UIBlurEffect(style: .Dark)
}

This will animate the blur radius from zero (totally transparent, or rather - no blur effect at all) to the default radius (fully blurred) over the duration of one second. And to do the reverse animation:

UIView.animateWithDuration(1.0) { () -> Void in
    blurView.effect = nil
}

The resulting animations transform the blur radius smoothly, even though you're actually adding/removing the blur effect entirely - UIKit just knows what to do behind the scenes.

Note that this wasn't always possible: Until recently (not sure when), a UIVisualEffectView had to be initialized with a UIVisualEffect, and the effect property was read-only. Now, effect is both optional and read/write (though the documentation isn't updated...), and UIVisualEffectView includes an empty initializer, enabling us to perform these animations.

The only restriction is that you cannot manually assign a custom blur radius to a UIVisualEffectView - you can only animate between 'no blur' and 'fully blurred'.

EDIT: In case anybody is interested, I've created a subclass of UIVisualEffectView that gives you full control over blur radius. The caveat is that it uses a private UIKit API, so you probably shouldn't submit apps for review using it. However, it's still interesting and useful for prototypes or internal applications: https://github.com/collinhundley/APCustomBlurView

Shalon answered 17/11, 2015 at 21:39 Comment(2)
what if you freeze the animation so that you can get somewhere between no blur and fully blurred? e.g. blurView.layer.timeOffset = 0.5Millstream
@Millstream I definitely wouldn't recommend that - you could end up with some weird results and it's likely to break in the future.Shalon

© 2022 - 2024 — McMap. All rights reserved.