how to speed up CABasicAnimation? - ios

I am using the following CABasicAnimation. But, its very slow..is there a way to speed it up ? Thanks.
- (void)spinLayer:(CALayer *)inLayer duration:(CFTimeInterval)inDuration
direction:(int)direction
{
CABasicAnimation* rotationAnimation;
// Rotate about the z axis
rotationAnimation =
[CABasicAnimation animationWithKeyPath:#"transform.rotation.z"];
// Rotate 360 degress, in direction specified
rotationAnimation.toValue = [NSNumber numberWithFloat: M_PI * 2.0 * direction];
// Perform the rotation over this many seconds
rotationAnimation.duration = inDuration;
// Set the pacing of the animation
rotationAnimation.timingFunction =
[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
// Add animation to the layer and make it so
[inLayer addAnimation:rotationAnimation forKey:#"rotationAnimation"];
}

Core Animation animations can repeat a number of times, by setting the repeatCount property on the animation.
So if you'd like to have an animation run for a total 80 seconds, you need to figure out a duration for one pass of the animation – maybe one full spin of this layer – and then set the duration to be that value. Then let the animation repeat that full spin several times to fill out your duration.
So something like this:
rotationAnimation.repeatCount = 8.0;
Alternatively, you can use repeatDuration to achieve a similar affect:
rotationAnimation.repeatDuration = 80.0;
In either case, you need to set the duration to the time of a single spin, and then repeat it using ONE of these methods. If you set both properties, the behavior is undefined. You can check out the documentation on CAMediaTiming here.

Related

CAAnimation is overriding previous CAAnimation animation

I have one this scenario:
I add to a layer CAAnimation that transforms it to a specific frame. with a starting time of 0.
Then I add another CAAnimation that transforms it to a different frame. with a starting time of 0.5.
what happens is that the layer immediately gets the second frame (with no animation) and after the first animation time passes the second animation is completed correctly.
This is the animation creation code:
+ (CAAnimation *)transformAnimation:(CALayer *)layer
fromFrame:(CGRect)fromFrame
toFrame:(CGRect)toFrame
fromAngle:(CGFloat)fromAngle
toAngle:(CGFloat)toAngle
anchor:(CGPoint)anchor
vertical:(BOOL)vertical
begin:(CFTimeInterval)begin
duration:(CFTimeInterval)duration {
CATransform3D fromTransform = makeTransform(layer, fromFrame, fromAngle, anchor, vertical);
CATransform3D midTransform1 = makeTransformLerp(layer, fromFrame, toFrame, fromAngle, toAngle, anchor, 0.33, vertical);
CATransform3D midTransform2 = makeTransformLerp(layer, fromFrame, toFrame, fromAngle, toAngle, anchor, 0.66, vertical);
CATransform3D toTransform = makeTransform(layer, toFrame, toAngle, anchor, vertical);
CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:#"transform"];
animation.values = #[[NSValue valueWithCATransform3D:fromTransform],
[NSValue valueWithCATransform3D:midTransform1],
[NSValue valueWithCATransform3D:midTransform2],
[NSValue valueWithCATransform3D:toTransform]
];
animation.beginTime = begin;
animation.duration = duration;
animation.fillMode = kCAFillModeBoth;
animation.calculationMode = kCAAnimationPaced;
animation.removedOnCompletion = NO;
return animation;
}
EDIT
in most scenarios, this code works well and the animations are sequenced correctly. But if I set 1 transform animation to start after 2 seconds and then set another transform to start after 4 seconds. the first transform is applied immediately to the layer and the second animation starts from there.
Any Idea how can I separate the animation to run one after the other?
(I prefer not using a completion block)
Thanks
The easiest and most glaring early fix would be to change the fill mode so that the second animation is not clamped on both ends overriding the previous animation.
animation.fillMode = kCAFillModeForwards;
Also I would adjust the begin time to be
animation.beginTime = CACurrentMediaTime() + begin;
If it is a matter of overlapping begin times and durations and not this let me know and I can provide that as well.

How can I calculate the duration of an ease-out animation to achieve a desired initial velocity?

Context:
I have a graphic that I rotate continuously while a background operation happens:
CABasicAnimation *rotationAnimation = [CABasicAnimation animationWithKeyPath:#"transform.rotation.z"];
rotationAnimation.toValue = #(M_PI * 2.0);
rotationAnimation.duration = 2;
rotationAnimation.cumulative = YES;
rotationAnimation.repeatCount = HUGE_VALF;
[myImgView.layer addAnimation:rotationAnimation forKey:#"rotationAnimation"];
At some point this background animation ends, and I stop the animation:
[myImgView.layer removeAllAnimations];
When I do this, though, the rotation stops wherever it is and snaps back to zero rotation. I could just stop it where it is by promoting the presentation value to the model value:
CATransform3D stoppedTransform = myImgView.layer.presentationLayer.transform;
[myImgView.layer removeAllAnimations];
myImgView.layer.transform = stoppedTransform;
This works OK. But ideally I'd like to continue the rotation for the rest of its current circuit, and decelerate and stop smoothly as it approaches and rests at zero rotation. Stop the animation, promote presentation to model, and create a new animation with an ease-out curve to zero. Something like this:
CATransform3D stoppedTransform = myImgView.layer.presentationLayer.transform;
[myImgView.layer removeAllAnimations];
myImgView.layer.transform = stoppedTransform;
CGFloat currRotation = [[myImgView.layer valueForKeyPath:#"transform.rotation.z"] floatValue];
CABasicAnimation *finishAnimation = [CABasicAnimation animationWithKeyPath:#"transform.rotation.z"];
finishAnimation.fromValue = #(currRotation);
finishAnimation.toValue = #(0);
finishAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
finishAnimation.duration = 2; //this is what I need to calculate correctly
[myImgView.layer setValue:#(0) forKeyPath:#"transform.rotation.z"];
[myImgView.layer addAnimation:finishAnimation forKey:#"transform.rotation.z"];
My question:
How do I calculate the duration of my finishing animation with its ease-out curve so that its initial velocity matches the velocity of the existing rotation (currently pi radians per second) so there's no visible hiccup? Or is there another way to achieve the desired effect?
I have tried using CASpringAnimation and using its initialVelocity property, but it seems to combine that with the velocity imparted by the spring pulling on the mass, which is governed by mass, stiffness, and damping, and its units are unclear. And I can get close on the ease-out duration by calculating the duration as if it's linear and bumping it 20% or 30% or so.
Side note: there is some minor complexity here, removed to simplify the question, around the toValue of finishAnimation because of how the layer reports its current rotation value. If it's more than pi radians (180 degrees), it reports as negative. So it goes like this:
CGFloat rotationRadians = currRotation / M_PI;
if (rotationRadians < 0)
{
finishAnimation.duration = (-1 * rotationRadians); //negative means more than halfway through, or more than pi radians.
finishAnimation.toValue = #(0);
}
else
{
finishAnimation.duration = (2 - rotationRadians); //positive means less than halfway through, or less than pi radians
finishAnimation.toValue = #(M_PI * 2);
}

Using CABasicAnimation to rotate a UIImageView more than once

I am using a CABasicAnimation to rotate a UIImageView 90 degrees clockwise, but I need to have it rotate a further 90 degrees later on from its position after the initial 90 degree rotation.
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:#"transform.rotation.z"];
animation.duration = 10;
animation.additive = YES;
animation.removedOnCompletion = NO;
animation.fillMode = kCAFillModeForwards;
animation.fromValue = [NSNumber numberWithFloat:DEGREES_TO_RADIANS(0)];
animation.toValue = [NSNumber numberWithFloat:DEGREES_TO_RADIANS(90)];
[_myview.layer addAnimation:animation forKey:#"90rotation"];
Using the code above works initially, the image stays at a 90 degree angle. If I call this again to make it rotate a further 90 degrees the animation starts by jumping back to 0 and rotating 90 degrees, not 90 to 180 degrees.
I was under the impression that animation.additive = YES; would cause further animations to use the current state as a starting point.
Any ideas?
tl;dr: It is very easy to misuse removeOnCompletion = NO and most people don't realize the consequences of doing so. The proper solution is to change the model value "for real".
First of all: I'm not trying to judge or be mean to you. I see the same misunderstanding over and over and I can see why it happens. By explaining why things happen I hope that everyone who experience the same issues and sees this answer learn more about what their code is doing.
What went wrong
I was under the impression that animation.additive = YES; would cause further animations to use the current state as a starting point.
That is very true and it's exactly what happens. Computers are funny in that sense. They always to exactly what you tell them and not what you want them to do.
removeOnCompletion = NO can be a bitch
In your case the villain is this line of code:
animation.removedOnCompletion = NO;
It is often misused to keep the final value of the animation after the animation completes. The only problem is that it happens by not removing the animation from the view. Animations in Core Animation doesn't alter the underlying property that they are animating, they just animate it on screen. If you look at the actual value during the animation you will never see it change. Instead the animation works on what is called the presentation layer.
Normally when the animation completes it is removed from the layer and the presentation layer goes away and the model layer appears on screen again. However, when you keep the animation attached to the layer everything looks as it should on screen but you have introduced a difference between what the property says is the transform and how the layer appears to be rotated on screen.
When you configure the animation to be additive that means that the from and to values are added to the existing value, just as you said. The problem is that the value of that property is 0. You never change it, you just animate it. The next time you try and add that animation to the same layer the value still won't be changed but the animation is doing exactly what it was configured to do: "animate additively from the current value of the model".
The solution
Skip that line of code. The result is however that the rotation doesn't stick. The better way to make it stick is to change the model. Set the new end value of the rotation before animating the rotation so that the model looks as it should when the animation gets removed.
byValue is like magic
There is a very handy property (that I'm going to use) on CABasicAnimation that is called byValue that can be used to make relative animations. It can be combined with either toValue and fromValue to do many different kinds of animations. The different combinations are all specified in its documentation (under the section). The combination I'm going to use is:
byValue and toValue are non-nil. Interpolates between (toValue - byValue) and toValue.
Some actual code
With an explicit toValue of 0 the animation happens from "currentValue-byValue" to "current value". By changing the model first current value is the end value.
NSString *zRotationKeyPath = #"transform.rotation.z"; // The killer of typos
// Change the model to the new "end value" (key path can work like this but properties don't)
CGFloat currentAngle = [[_myview.layer valueForKeyPath:zRotationKeyPath] floatValue];
CGFloat angleToAdd = M_PI_2; // 90 deg = pi/2
[_myview.layer setValue:#(currentAngle+angleToAdd) forKeyPath:zRotationKeyPath];
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:zRotationKeyPath];
animation.duration = 10;
// #( ) is fancy NSNumber literal syntax ...
animation.toValue = #(0.0); // model value was already changed. End at that value
animation.byValue = #(angleToAdd); // start from - this value (it's toValue - byValue (see above))
// Add the animation. Once it completed it will be removed and you will see the value
// of the model layer which happens to be the same value as the animation stopped at.
[_myview.layer addAnimation:animation forKey:#"90rotation"];
Small disclaimer:
I didn't run this code but am fairly certain that it runs as it should and that I didn't do any typos. Correct me if I did. The entire discussion is still valid.
pass incremental value of angle see my code
static int imgAngle=0;
- (void)doAnimation
{
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:#"transform.rotation.z"];
animation.duration = 5;
animation.additive = YES;
animation.removedOnCompletion = NO;
animation.fillMode = kCAFillModeForwards;
animation.fromValue = [NSNumber numberWithFloat:DEGREES_TO_RADIANS(imgAngle)];
animation.toValue = [NSNumber numberWithFloat:DEGREES_TO_RADIANS(imgAngle+90)];
[self.imgView.layer addAnimation:animation forKey:#"90rotation"];
imgAngle+=90;
if (imgAngle>360) {
imgAngle = 0;
}
}
Above code is just for idea. Its not tested

CABasicAnimation - Animating between two angles

I'm attempting to create an animated CALayer that uses a CABasicAnimation in order to animate an object that rotates at discrete intervals between two angles. Note the word discrete: I'm not trying to create a continuous animation between two points, but rather I want to calculate fixed increments between each angle in order to create a discrete movement feel.
Here's a diagram:
I've looked into setting the byValue attribute of the CABasicAnimation, but I can't seem to get it to work since you can't use fromValue, ToValue, and byValue in one animation. fromValue is always from zero, so I guess that could be dropped, but it still never animates correctly when using the current endAngle as the toValue and a byValue of 0.1 (arbitrarily chosen but should work for testing). Any ideas on how to implement this? Here's code I'm using:
anim = [CABasicAnimation animationWithKeyPath:#"currentEndAngle"];
anim.duration = 0.5f;
anim.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
anim.toValue = [NSNumber numberWithFloat:self.endAngle];
anim.byValue = [NSNumber numberWithFloat:0.1f];
anim.repeatCount = HUGE_VALF;
[anim setDelegate:self];
[self addAnimation:anim forKey:#"animKey"];
Thanks!

Core Animation - Play 2 Animations in Sequence

I'm trying to put together an animation that works a little like a speedometer.
The first animation gets the needle
CFTimeInterval localMediaTime = [needle convertTime:CACurrentMediaTime() fromLayer:nil];
CABasicAnimation *needAni = [CABasicAnimation animationWithKeyPath:#"transform.rotation.z"];
needAni.duration = 0.5f;
needAni.fromValue = [NSNumber numberWithFloat:0.0];
needAni.toValue = [NSNumber numberWithFloat:(rotVal * M_PI / 180.0)];
needAni.timingFunction = [CAMediaTimingFunction functionWithControlPoints:0.195: 0.600: 0.790: 0.405];
needAni.fillMode = kCAFillModeBackwards;
[needle.layer addAnimation:needAni forKey:nil];
After that plays I would like to have the needle bounce back and forth a little when its reached full speed. This animation does just that:
CABasicAnimation *needAni2 = [CABasicAnimation animationWithKeyPath:#"transform.rotation.z"];
needAni2.duration = 0.1f;
needAni2.fromValue = [NSNumber numberWithFloat:(rotVal * M_PI / 180.0)];
needAni2.toValue = [NSNumber numberWithFloat:((rotVal+5) * M_PI / 180.0)];
needAni2.fillMode = kCAFillModeBackwards;
needAni2.autoreverses = YES;
needAni2.repeatCount = HUGE_VAL;
needAni2.beginTime = localMediaTime + 0.5f;
[needle.layer addAnimation:needAni2 forKey:nil];
Now when I put this together only the second animation plays.
I tired putting these two animations into a group, but I can't seem to just repeat the second animation, it repeats the whole process. Is there a performance problem if I put the group duration equal to HUGE_VAL or is there a better way to do this?
Thanks
I think you can just stick with your method, as this seems to be the intended usage of CAGroupAnimation. Just make sure you set an appropriate duration for the group. If you make the duration for the group shorter than your intended animations, it will cut your animations short. If you make the duration longer than your animations, the animation objects might possibly linger in memory until that duration is over.
Another option would be to implement the delegate method -animationDidStop:finished: , and add the second animation when that gets called by the first animation.
CAAnimation reference:
https://developer.apple.com/library/ios/#documentation/GraphicsImaging/Reference/CAAnimation_class/Introduction/Introduction.html#//apple_ref/occ/cl/CAAnimation

Resources