CALayer CABasicAnimation chaining - ios

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?

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) :)).

A CABasicAnimation can have a delegate. The delegate will be sent animationDidStop:finished:. Now you can ask for the next animation in the chain.
In your case, though, you don't even need that; just use an animation where autoreverses is YES.
(Oh, and do not mess with removedOnCompletion and fillMode; that's just wrong, and examples that use them are equally wrong. They are needed only in the middle complex grouped animations.)

Related

I set the toValue of rotation to 2*PI, but why after the animation these views are not horizontal?

Codes are as follows:
CABasicAnimation *rotateWhenBoom = [CABasicAnimation animationWithKeyPath:#"transform.rotation.z"];
rotateWhenBoom.fromValue = #0;
rotateWhenBoom.toValue = #(M_PI*2.0);
rotateWhenBoom.duration = 0.3f;
rotateWhenBoom.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
CAAnimationGroup *boom = [CAAnimationGroup animation];
boom.animations = #[[self moveOutWithBtn:btn], rotateWhenBoom];
boom.fillMode = kCAFillModeForwards;
boom.removedOnCompletion = NO;
And the effect:
effect
Before the animation the views are all horizontal. I add a rotation animation to these views, and the toValue of rotation is 2*PI. Why after the animation they are not horizontal?
Thanks in advance!!
Your last two lines of code:
boom.fillMode = kCAFillModeForwards;
boom.removedOnCompletion = NO;
mean that the layer stays at the final state of animation and that the animation is not automatically removed from the layer when it completes. You probably want to remove the last line boom.removeOnCompletion = NO
A good guide for CALayer and CAAnimation that explains this: https://www.objc.io/issues/12-animations/animations-explained/

Animating both position and rotation in CAAnimationGroup makes position not updated in the end

I was trying to animate both position and rotation property of a UIView using an explicit animation and the result is that the rotation was successfully updated but the position of the view did not update although I updated both the layer's position and rotation property to its final value right after I add the animation to the view's layer(I guess it is so called explicit-override-implicit animation technique?).
Here is my code:
CABasicAnimation *move = [CABasicAnimation animationWithKeyPath:#"position.y"];
move.fromValue = #(self.square.center.y);
move.toValue = #(300);
CABasicAnimation *rotate = [CABasicAnimation animationWithKeyPath:#"transform.rotation.z"];
rotate.fromValue = #(DEGREES_TO_RADIANS(0));
rotate.toValue = #(DEGREES_TO_RADIANS(45));
CAAnimationGroup *group = [CAAnimationGroup animation];
group.duration = 1.0;
group.animations = #[move, rotate];
self.square.center = CGPointMake(self.square.center.x, 300);
self.square.transform = CGAffineTransformMakeRotation(M_PI/4);
[self.square.layer addAnimation:group forKey:nil];
If I implement the position or rotation animation separately, the code performs well and I got the expected results. But when it combines into the CAAnimationGroup, the position just won't update to the final value in the end.
Any ideas here?
Maybe try this: of course with your values:
[UIView animateWithDuration:1.0f animations:^{
self.square.center = CGPointMake(10, 10);
self.square.transform =CGAffineTransformMakeRotation(90);
}completion:nil];

Cannot get current position of CALayer during animation

I am trying to achieve an animation that when you hold down a button it animates a block down, and when you release, it animates it back up to the original position, but I cannot obtain the current position of the animating block no matter what. Here is my code:
-(IBAction)moveDown:(id)sender{
CGRect position = [[container.layer presentationLayer] frame];
[movePath moveToPoint:CGPointMake(container.frame.origin.x, position.y)];
[movePath addLineToPoint:CGPointMake(container.frame.origin.x, 310)];
CAKeyframeAnimation *moveAnim = [CAKeyframeAnimation animationWithKeyPath:#"position"];
moveAnim.path = movePath.CGPath;
moveAnim.removedOnCompletion = NO;
moveAnim.fillMode = kCAFillModeForwards;
CAAnimationGroup *animGroup = [CAAnimationGroup animation];
animGroup.animations = [NSArray arrayWithObjects:moveAnim, nil];
animGroup.duration = 2.0;
animGroup.removedOnCompletion = NO;
animGroup.fillMode = kCAFillModeForwards;
[container.layer addAnimation:animGroup forKey:nil];
}
-(IBAction)moveUp:(id)sender{
CGRect position = [[container.layer presentationLayer] frame];
UIBezierPath *movePath = [UIBezierPath bezierPath];
[movePath moveToPoint:CGPointMake(container.frame.origin.x, position.y)];
[movePath addLineToPoint:CGPointMake(container.frame.origin.x, 115)];
CAKeyframeAnimation *moveAnim = [CAKeyframeAnimation animationWithKeyPath:#"position"];
moveAnim.path = movePath.CGPath;
moveAnim.removedOnCompletion = NO;
moveAnim.fillMode = kCAFillModeForwards;
CAAnimationGroup *animGroup = [CAAnimationGroup animation];
animGroup.animations = [NSArray arrayWithObjects:moveAnim, nil];
animGroup.duration = 2.0;
animGroup.removedOnCompletion = NO;
animGroup.fillMode = kCAFillModeForwards;
[container.layer addAnimation:animGroup forKey:nil];
}
But the line
CGRect position = [[container.layer presentationLayer] frame];
is only returning the destination position not the current position. I need to basically give me the current position of the container thats animating once I release the button, so I can perform the next animation. What I have now does not work.
I haven't analyzed your code enough to be 100% sure why [[container.layer presentationLayer] frame] might not return what you expect. But I see several problems.
One obvious problem is that moveDown: doesn't declare movePath. If movePath is an instance variable, you probably want to clear it or create a new instance each time moveDown: is called, but I don't see you doing that.
A less obvious problem is that (judging from your use of removedOnCompletion and fillMode, in spite of your use of presentationLayer) you apparently don't understand how Core Animation works. This turns out to be surprisingly common, so forgive me if I'm wrong. Anyway, read on, because I will explain how Core Animation works and then how to fix your problem.
In Core Animation, the layer object you normally work with is a model layer. When you attach an animation to a layer, Core Animation creates a copy of the model layer, called the presentation layer, and the animation changes the properties of the presentation layer over time. An animation never changes the properties of the model layer.
When the animation ends, and (by default) is removed, the presentation layer is destroyed and the values of the model layer's properties take effect again. So the layer on screen appears to “snap back” to its original position/color/whatever.
A common, but wrong way to fix this is to set the animation's removedOnCompletion to NO and its fillMode to kCAFillModeForwards. When you do this, the presentation layer hangs around, so there's no “snap back” on screen. The problem is that now you have the presentation layer hanging around with different values than the model layer. If you ask the model layer (or the view that owns it) for the value of the animated property, you'll get a value that's different than what's on screen. And if you try to animate the property again, the animation will probably start from the wrong place.
To animate a layer property and make it “stick”, you need to change the model layer's property value, and then apply the animation. That way, when the animation is removed, and the presentation layer goes away, the layer on screen will look exactly the same, because the model layer has the same property values as its presentation layer had when the animation ended.
Now, I don't know why you're using a keyframe to animate straight-line motion, or why you're using an animation group. Neither seems necessary here. And your two methods are virtually identical, so let's factor out the common code:
- (void)animateLayer:(CALayer *)layer toY:(CGFloat)y {
CGPoint fromValue = [layer.presentationLayer position];
CGPoint toValue = CGPointMake(fromValue.x, y);
layer.position = toValue;
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:#"position"];
animation.fromValue = [NSValue valueWithCGPoint:fromValue];
animation.toValue = [NSValue valueWithCGPoint:toValue];
animation.duration = 2;
[layer addAnimation:animation forKey:animation.keyPath];
}
Notice that we're giving the animation a key when I add it to the layer. Since we use the same key every time, each new animation will replace (remove) the prior animation if the prior animation hasn't finished yet.
Of course, as soon as you play with this, you'll find that if you moveUp: when the moveDown: is only half finished, the moveUp: animation will appear to be at half speed because it still has a duration of 2 seconds but only half as far to travel. We should really compute the duration based on the distance to be travelled:
- (void)animateLayer:(CALayer *)layer toY:(CGFloat)y withBaseY:(CGFloat)baseY {
CGPoint fromValue = [layer.presentationLayer position];
CGPoint toValue = CGPointMake(fromValue.x, y);
layer.position = toValue;
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:#"position"];
animation.fromValue = [NSValue valueWithCGPoint:fromValue];
animation.toValue = [NSValue valueWithCGPoint:toValue];
animation.duration = 2.0 * (toValue.y - fromValue.y) / (y - baseY);
[layer addAnimation:animation forKey:animation.keyPath];
}
If you really need it to be a keypath animation in an animation group, your question should show us why you need those things. Anyway, it works with those things too:
- (void)animateLayer:(CALayer *)layer toY:(CGFloat)y withBaseY:(CGFloat)baseY {
CGPoint fromValue = [layer.presentationLayer position];
CGPoint toValue = CGPointMake(fromValue.x, y);
layer.position = toValue;
UIBezierPath *path = [UIBezierPath bezierPath];
[path moveToPoint:fromValue];
[path addLineToPoint:toValue];
CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:#"position"];
animation.path = path.CGPath;
animation.duration = 2.0 * (toValue.y - fromValue.y) / (y - baseY);
CAAnimationGroup *group = [CAAnimationGroup animation];
group.duration = animation.duration;
group.animations = #[animation];
[layer addAnimation:group forKey:animation.keyPath];
}
You can find the full code for my test program in this gist. Just create a new Single View Application project and replace the contents of ViewController.m with the contents of the gist.

UIButton doesn't receive touch after CAKeyframeAnimation

My situation:
I've a UIButton that it's animate with a CAKeyframeAnimation that's declared as a category on UIView:
CAKeyframeAnimation * scale = [CAKeyframeAnimation animationWithKeyPath:#"transform.scale"];
scale.duration = duration;
scale.beginTime = delay;
scale.fillMode = kCAFillModeForwards;
NSMutableArray * times = [[NSMutableArray alloc] init];
scale.values = values;
scale.timingFunctions = times;
CAAnimationGroup * group = [CAAnimationGroup animation];
[group setDelegate:self];
[group setDuration:duration + delay];
[group setFillMode:kCAFillModeForwards];
[group setRemovedOnCompletion:NO];
[group setAnimations:[NSArray arrayWithObject:scale]];
[self.layer addAnimation:group forKey:#"scale"];
The problem is that after the animation, the button doesn't receive touch. If I remove the animation all works fine.
Does anyone know what I'm doing wrong ?
Thanks
You shouldn't use kCAFillModeForwards and removedOnCompletion = NO to stick the animated layer in the final position. This will not work for a control, and results in the behavior you noticed.
Instead, set the final state for the button before adding the animation to it's layer.
self.layer.transform = CGAffineTransformMakeScale(finalScaleX, finalScaleY);
[self.layer addAnimation:group forKey:#"scale"];
The problem is that the animation only changes the presentation of the button but the touch target is still the same as before. You should either remove the animation after completion and set the transform on the button or ht test the presentation layer.
I wrote about hit testing animating layers in a blog post that explains it in more detail.
You must insert the following line of code self.layer.transform = CGAffineTransformMakeScale(finalScaleX, finalScaleY); when the animation is ended.

CAAnimationGroup reverts to original position on completion

In iOS I'm trying to create the effect of an icon shrinking in size, and flying across the screen in an arc while fading out, and then disappearing. I've achieved these 3 effects with an CAAnimationGroup, and it does what I want. The problem is when the animation ends, the view appears back at the original position, full size and full opacity. Can anyone see what I am doing wrong in the code below?
The animation should not revert to it's original position, but just disappear at the end.
UIBezierPath *movePath = [UIBezierPath bezierPath];
CGPoint libraryIconCenter = CGPointMake(610, 40);
CGPoint ctlPoint = CGPointMake(self.imgViewCropped.center.x, 22.0);
movePath moveToPoint:self.imgViewCropped.center];
[movePath addQuadCurveToPoint:libraryIconCenter
controlPoint:ctlPoint];
CAKeyframeAnimation *moveAnim = [CAKeyframeAnimation animationWithKeyPath:#"position"];
moveAnim.path = movePath.CGPath;
moveAnim.removedOnCompletion = NO;
CABasicAnimation *scaleAnim = [CABasicAnimation animationWithKeyPath:#"transform"];
scaleAnim.fromValue = [NSValue valueWithCATransform3D:CATransform3DIdentity];
scaleAnim.toValue = [NSValue valueWithCATransform3D:CATransform3DMakeScale(0.1, 0.1, 1.0)];
scaleAnim.removedOnCompletion = NO;
CABasicAnimation *opacityAnim = [CABasicAnimation animationWithKeyPath:#"alpha"];
opacityAnim.fromValue = [NSNumber numberWithFloat:1.0];
opacityAnim.toValue = [NSNumber numberWithFloat:0.0];
opacityAnim.removedOnCompletion = NO;
CAAnimationGroup *animGroup = [CAAnimationGroup animation];
animGroup.animations = [NSArray arrayWithObjects:moveAnim,scaleAnim,opacityAnim, nil];
animGroup.duration = 0.6;
animGroup.delegate = self;
animGroup.removedOnCompletion = NO;
[self.imgViewCropped.layer addAnimation:animGroup forKey:nil];
I believe you need to set the fillMode property of your animations to kCAFillModeForwards. That should freeze the animations at their end time. Another suggestion (and honestly, this is what I'd usually do) is just se the properties of the layer itself to their final position after you've set up the animation. That way when the animation is removed, the layer will still have the final properties as part of its model.
As an aside, the removedOnCompletion flag of animations contained within a CAAnimationGroup is ignored. You should probably just remove those assignments since they're misleading. Replace them with assignments to fillMode as specified above.

Resources