Android
iOS
 

Create an Animation Group

This recipe shows how to create an animation that groups multiple animations together using Core Animation.

Recipe



Follow these steps to create the animation:

  • Add an image named sample.png to the project with a Build Action of Content.
  • In a UIViewController subclass, declare a CALayer class variable from the MonoTouch.CoreAnimation namespace.
CALayer _layer;
  • 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;
  • Add the layer as a sub layer of the view’s layer.
View.Layer.AddSublayer (_layer);
  • In the ViewWillAppear method, add the following code to create the animations.
var pt = _layer.Position;
_layer.Position = new PointF (100, 300);
var basicAnimation = CABasicAnimation.FromKeyPath ("position");
basicAnimation.TimingFunction = CAMediaTimingFunction.FromName (CAMediaTimingFunction.EaseInEaseOut);
basicAnimation.From = NSValue.FromPointF (pt);
basicAnimation.To = NSValue.FromPointF (new PointF (100, 300));
_layer.Transform = 
CATransform3D.MakeRotation ((float)Math.PI * 2, 0, 0, 1);       
var 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);
var animationGroup = CAAnimationGroup.CreateAnimation ();
animationGroup.Duration = 2;
animationGroup.Animations = 
new CAAnimation[] { basicAnimation, animRotate };
_layer.AddAnimation (animationGroup, null);

Additional Information

The code creates 2 separate explicit animations. The first animation is a CABasicAnimation that animates the layer’s position. The second animation is a CAKeyFrameAnimation that rotates the layer. These animations are combined into a CAAnimationGroup that is added to the layer.