views:

187

answers:

2

I try to do this: There is an view which has been rotated already to some value, lets say 15 degrees.

Imagine a view rotated by 15 degrees.

Next, I only know, that I want this view to rotate from it's current rotation to 40 degrees.

Imagine how that view now rotates from 15 to 40 degrees.

For practice, I want to do that with CAKeyFrameAnimation. But the thing is, all I can do there is to hard-specify from where to where. There's no convenient "pick up current state" thing like UIView animations have, right? How would I go about it?

Also, I want to specify always 3 keyframes for that rotation, no matter how much the needed amount of rotation is.

Imagine how that view rotates from 15 to 40 degrees, using 3 keyframes to do so

But another big problem: It might happen, that another animation has to kick in with a different target. lets say a view is currently rotation from 20 to 100 degrees, and just somewhere inbetween the animation a new animation is kicked and wants that view to go to 15 degrees. With UIView animations that's simple. How to do that with CAKeyFrameAnimation?

Basically I want it to behave like UIView animations which pick up current state ;)

CALayer* theLayer = rotatedView.layer;

CAKeyframeAnimation* animation;
animation = [CAKeyframeAnimation animationWithKeyPath:@"transform.rotation.z"];

animation.duration = 2;
animation.repeatCount = 1;
animation.removedOnCompletion = NO;
animation.fillMode = kCAFillModeForwards;

animation.values = [NSArray arrayWithObjects:
                    [NSNumber numberWithFloat:(10.0 / 180.0) * M_PI],
                    [NSNumber numberWithFloat:(20.0 / 180.0) * M_PI],
                    [NSNumber numberWithFloat:(30.0 / 180.0) * M_PI], nil];

[theLayer addAnimation:animation forKey:@"transform.rotation.z"];
A: 

You can use theLayer.transform or theLayer.affineTransform to get the current transform matrix (before the animation), then use http://stackoverflow.com/questions/2051811 to get the angle to start with.

KennyTM
I added a comment there... not really clear ;)
openfrog
A: 

You can obtain the starting angle for use in setting up your animation either using code like what I provide in this answer:

CATransform3D rotationTransform = [theLayer transform];
float angle;
if (rotationTransform.m11 < 0.0f)
        angle = 180.0f - (asin(rotationTransform.m12) * 180.0f / M_PI);
else
        angle = asin(rotationTransform.m12) * 180.0f / M_PI;

or using the simpler helper keypath method suggested here:

float currentAngle = ([[theLayer valueForKeyPath:@"transform.rotation.z"] floatValue] * 180.0f / M_PI);

If you are adding this animation to one already in progress, you will need to query the current angle of theLayer's presentationLayer, instead of theLayer directly. The presentationLayer for a CALayer reflects the current state of a layer mid-animation.

Brad Larson