I am trying to animate the transform
property of a view. Here is my code:
CAKeyframeAnimation *shakeAnimation = [CAKeyframeAnimation animationWithKeyPath:@"transform"];
NSArray *transformValues = [NSArray arrayWithObjects:
[NSValue valueWithCGAffineTransform:CGAffineTransformMakeRotation((3*M_PI)/8)],
[NSValue valueWithCGAffineTransform:CGAffineTransformMakeRotation(-((3*M_PI)/8))],
[NSValue valueWithCGAffineTransform:CGAffineTransformMakeRotation((3*M_PI)/8)],
[NSValue valueWithCGAffineTransform:CGAffineTransformMakeRotation(-((3*M_PI)/8))],
[NSValue valueWithCGAffineTransform:CGAffineTransformMakeRotation((3*M_PI)/8)],
[NSValue valueWithCGAffineTransform:CGAffineTransformMakeRotation(-((3*M_PI)/8))],
nil];
[shakeAnimation setValues:transformValues];
NSArray *times = [NSArray arrayWithObjects:[NSNumber numberWithFloat:0.16f],[NSNumber numberWithFloat:0.33f],[NSNumber numberWithFloat:0.49f],[NSNumber numberWithFloat:0.66f],[NSNumber numberWithFloat:0.82f], [NSNumber numberWithFloat:1.0f], nil];
[shakeAnimation setKeyTimes:times];
NSArray *timingFunctions = [NSArray arrayWithObjects:
[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut],
[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut],
[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut],
[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut],
[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut],
[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut],
nil];
[shakeAnimation setTimingFunctions:timingFunctions];
shakeAnimation.fillMode = kCAFillModeForwards;
shakeAnimation.removedOnCompletion = NO;
shakeAnimation.duration = 1.0f;
[self.someView.layer addAnimation:shakeAnimation forKey:@"anim"];
For some reason, I get an error whenever I set the parameter of the method animationWithKeyPath:
to "transform". I have tried for half an hour to debug this, but can't find the error. I initially though that I was performing an animation not allowed on a UIView's transform property, but I know that I can do something like this:
aView.transform = CGAffineTransformMakeRotation(M_PI/2);
Thanks in advanced.
The value of a layer's transform
property is a CATransform3D
, not a CGAffineTransform
.
Also, you might find it simpler to animate the transform.rotation.z
key path. The value is just a CGFloat
, so you don't have to create a transform matrix at all.
“Modifying a Transform Using Key Paths” in Core Animation Programming Guide
“Key Path Support for Structure Fields” in Core Animation Programming Guide