Android
iOS
 

Create a Keyframe Animation

This recipe shows how to create a keyframe animation using Core Animation.

Recipe

Follow these steps to create the animation:

  1. Add an image named sample.png to the project with a Build Action of Content.
  2. In a UIViewController subclass, declare a CALayer class variable from the MonoTouch.CoreAnimation namespace.
CALayer _layer;
  1. In ViewDidLoad method, create the layer and set its content to be the image.
_layer = new CALayer ();

_layer.Bounds = new RectangleF (0, 0, 50, 50);

_layer.Position = new PointF (UIScreen.MainScreen.Bounds.Width / 2,     UIScreen.MainScreen.Bounds.Height / 2);

_layer.Contents = UIImage.FromFile ("sample.png").CGImage;

_layer.ContentsGravity = CALayer.GravityResizeAspectFill;
  1. Add the layer as a sub layer of the view’s layer.
View.Layer.AddSublayer (_layer);
  1. In the ViewWillAppear method, add the following code.
_layer.Transform = CATransform3D.MakeRotation (
       (float)Math.PI * 2, 0, 0, 1);
           
CAKeyFrameAnimation animRotate = (CAKeyFrameAnimation)CAKeyFrameAnimation.FromKeyPath ("transform");       

animRotate.Values = new NSObject[] {
       NSNumber.FromFloat (0f),
       NSNumber.FromFloat ((float)Math.PI / 2f),
       NSNumber.FromFloat ((float)Math.PI),
       NSNumber.FromFloat ((float)Math.PI * 2)};
  
animRotate.ValueFunction = CAValueFunction.FromName (CAValueFunction.RotateX);         

animRotate.Duration = 2;

_layer.AddAnimation (animRotate, "transform");

Additional Information

The code creates a CAKeyframeAnimation to animate the layer’s transform. The animation interpolates across the values set via an array. The value function is used to cause the animation to rotate the layer about the x-axis. As an animation does not change the actual value of the transform, but only the presentation, the code sets the transform to the final value presented by the animation in order for the layer to remain at the final value when the animation completes.