Dan Morrow Dan Morrow - 3 months ago 25
iOS Question

How can blurriness of UIVisualEffectView be modified while dragging in iOS?

Currently, I'm using a UIVisualEffectView to apply a blur to an image.

I have a UIScrollView. As I pull down on the scrollView, in my "scrollViewDidScroll" method, I'm changing the alpha of the UIVisualEffectView. The current behavior of this is that the blur radius changes smoothly as I drag around in the view.

The problem is, of course, I'm not supposed to be doing this. Getting warnings about changing the alpha value of a UIVisualEffectView.

I've seen people say to do a smooth transition of blurring using an animation, like this here: How does one fade a UIVisualEffectView and/or UIBlurEffect in and out?

However, I haven't seen anything that allows me to do this during, say a pan-gesture or something. I mean, if I set up an animation with a timed amount, all good. But doing this during a drag?

Answer

There is a way :)

As you've noticed, you can animate from a nil effect to an effect like UIBlurEffectStyleDark so if we add an animation and then pause the layer's animations we can control the progress of the effect by adjusting the layer's timeOffset!

- (void) setupBlur {
    // Setup the blur to start with no effect
    self.blurredEffectView = [[UIVisualEffectView alloc] initWithEffect:nil];

    // Add animation to desired blur effect
    [UIView animateWithDuration:1.0 animations:^{
        [self.blurredEffectView setEffect:[UIBlurEffect effectWithStyle:UIBlurEffectStyleDark]];
    }];

    // Pause layer animations
    self.blurredEffectView.layer.speed = 0;
}

Adjust blur between 0.0 and 1.0 (animation duration):

- (void) adjustBlur:(CGFloat)blurIntensity {
    self.blurredEffectView.layer.timeOffset = blurIntensity;
}
  • Note: this won't work on iOS 8 where UIBlurEffect animations aren't supported.