CABasic Animation Rotation

Go To StackoverFlow.com

0

I am using a simple CABasic Animation to rotate an image within a View. When the user touches the image, touches began is called to allow the rotation to begin. Touches Ended is then called when the user finishes rotating the image.

Once Touches Ended I have then rotate the image again to a fixed point. Here's the code

CABasicAnimation *rotation = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];

double startRotationValue = 0;
rotation.fromValue = [NSNumber numberWithDouble:startRotationValue];
rotation.toValue = [NSNumber numberWithDouble:startRotationValue+0.25];
rotation.duration = 1.0;
rotation.fillMode = kCAFillModeForwards;
rotation.removedOnCompletion = NO;

[self.view.layer addAnimation:rotation forKey:@"rotating"];

This works fine until the image is selected for a second time. Touches began is called again but the image cannot be rotated. In fact the image cannot be moved at all I know it is something to do with

rotation.fillMode = kCAFillModeForwards;
rotation.removedOnCompletion = NO;

I have tried to call removedOnCompletion in Touches began which does not solve the problem.

rotation.removedOnCompletion = YES

Whats the best approach here, somehow the View is not registering rotation.removedOnCompletion correctly.

2012-04-04 00:35
by user494088


1

First, you generally shouldn't mess with fillMode and removedOnCompletion. Remove these entirely. Those who tell you to mess with them are almost always fixing the wrong problem.

The problem they mean to fix is that when the animation completes and is removed, the object "snaps back" to its old location. The reason for that is you never actually set the value on the model. This creates all kinds of little annoying problems later.

After this line:

[self.view.layer addAnimation:rotation forKey:@"rotating"];

Add:

self.view.layer.transform.rotation = startRotationValue + 0.25;

(You may have to use a temporary variable here to hold the transform, modify it, and then set it back. I typically don't use the rotation attribute myself.)

This will set the underlying model layer so that it matches the final state of the animation.

2012-04-04 02:43
by Rob Napier
Interesting, many posts on here refer to using fillmode and removeOnCompletion to avoid the animation snapping back to its start position. I'll experiment with the transform to avoid the same scenario, thanks - user494088 2012-04-04 08:36