Animating a gaussian blur using core animation?

2019-03-10 04:03发布

I'm trying to animate something where it's initially blurry then it comes into focus. I guess it works OK, but when the animation is done it's still a little blurry. Am I doing this wrong?

CABasicAnimation* blurAnimation = [CABasicAnimation animation];
CIFilter *blurFilter = [CIFilter filterWithName:@"CIGaussianBlur"];
[blurFilter setDefaults];
[blurFilter setValue:[NSNumber numberWithFloat:0.0] forKey:@"inputRadius"];
[blurFilter setName:@"blur"];
[[self layer] setFilters:[NSArray arrayWithObject:blurFilter]];

blurAnimation.keyPath = @"filters.blur.inputRadius";
blurAnimation.fromValue = [NSNumber numberWithFloat:10.0f];
blurAnimation.toValue = [NSNumber numberWithFloat:1.0];
blurAnimation.duration = 1.2;

[self.layer addAnimation:blurAnimation forKey:@"blurAnimation"];

2条回答
Bombasti
2楼-- · 2019-03-10 04:31

Your problem is that the animation stops and is automatically removed, but the filter lingers with the tiniest of blur applied.

What you want to do is to remove the blur filter when the animation completes. You need to add a delegate to the CABasicAnimation instance and implement the -[id<CAAnimationDelegate> animationDidStop:finished:] method.

If you let self be the delegate in this case it should be fairly simple, add this line before adding the animation to your layer:

blurAnimation.delegate = self;

And the callback is equally simple:

- (void)animationDidStop:(CAAnimation *)theAnimation finished:(BOOL)flag {
    [[self layer] setFilters:nil];
}
查看更多
趁早两清
3楼-- · 2019-03-10 04:34

If you're looking for an optimized way to animate a blur then I recommend creating a single blurred image of your view and then fading the blurred image from alpha 0 to 1 over the top of your original view. Seems nice and fast in tests.

查看更多
登录 后发表回答