Search code examples
ioscalayercabasicanimation

CALayer CABasicAnimation chaining


I'm animating a CALayer's opacity-property with the following code:

Creating the animation in a method:

+ (CABasicAnimation *)fadeIn:(float)begin duration:(float)duration remove:(BOOL)remove{

    CABasicAnimation *fadeAnimation = [CABasicAnimation animationWithKeyPath:@"opacity"];
    fadeAnimation.fromValue = [NSNumber numberWithFloat:0.0];
    fadeAnimation.toValue = [NSNumber numberWithFloat:1.0];
    fadeAnimation.additive = NO;
    fadeAnimation.removedOnCompletion = remove;
    fadeAnimation.beginTime = begin;
    fadeAnimation.duration = duration;
    fadeAnimation.fillMode = kCAFillModeBoth;

    return fadeAnimation;
}

Adding the animation to the layer:

[overlayLayer addAnimation:[VideoComposerHelpers fadeIn:1.0 duration:0.5 remove:NO] forKey:nil];

This is working perfect. However, now I want to add another animation to the same layer, right after the first animation finished.

[overlayLayer addAnimation:[VideoComposerHelpers fadeOut:1.5 duration:0.5 remove:NO] forKey:nil]; // fadeOut is a method similar to fadeIn

What should happen is, the layer fades in with a duration of 0.5 and right after that, it fades out with a duration of 0.5. This doesn't seem to work, though. Is it because the start point of the second animation is the same as the end point of the first one?


Solution

  • You should use a CAAnimationGroup something like this:

    CABasicAnimation *fadeIn  = [VideoComposerHelpers fadeIn:1.0 duration:0.5 remove:NO];
    CABasicAnimation *fadeOut = [VideoComposerHelpers fadeOut:1.5 duration:0.5 remove:NO];
    
    CAAnimationGroup *group = [CAAnimationGroup animation];
    group.fillMode = kCAFillModeForwards;
    group.removedOnCompletion = NO;
    [group setAnimations:[NSArray arrayWithObjects:fadeIn, fadeOut, nil]];
    group.duration = 2;
    [overlayLayer addAnimation:group forKey:@"savingAnimation"];
    

    Also I'm not sure if I get the right values vor start, end, duration of the animations (you should check them) :)).