Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Animating UIVisualEffectView Blur Radius?

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.

like image 512
Brave Heart Avatar asked Mar 26 '15 12:03

Brave Heart


1 Answers

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

like image 114
Hundley Avatar answered Nov 02 '22 12:11

Hundley