Cross Platform
Android
iOS
Mac
Test Cloud

Walkthrough - Using CoreGraphics and CoreAnimation

This article demonstrates step by step how to create an application that uses Core Graphics and Core Animation. It shows how to draw on the screen in response to user touch as well as how to animate an image to travel along a path.

Drawing and Animating Along a Path

For this walkthrough we are going to draw a path using Core Graphics in response to touch input. Then, we are code to add a CALayer containing an image that we will animate along the path.

The following screenshot shows the completed application:

Images/00_final_app.png

Drawing a Path

Open the GraphicsDemo starter project that accompanies this article and open the DemoView class.

In DemoView add a CGPath variable to the class and instantiate it in the constructor. Also declare to PointF variable that we will use to capture the touch point that we construct the path from:

public class DemoView : UIView
{
    CGPath path;
    PointF initialPoint;
    PointF latestPoint;

    public DemoView ()
    {
        BackgroundColor = UIColor.White;

        path = new CGPath ();
    }
}

Next, override TouchesBegan and TouchesMoved, and add the following implementations to capture the initial touch point and each subsequent touch point respectively:

public override void TouchesBegan (MonoTouch.Foundation.NSSet touches, UIEvent evt)
{
    base.TouchesBegan (touches, evt);

    UITouch touch = touches.AnyObject as UITouch;

    if (touch != null) {
        initialPoint = touch.LocationInView (this);
    }
}

public override void TouchesMoved (MonoTouch.Foundation.NSSet touches, UIEvent evt)
{
    base.TouchesMoved (touches, evt);

    UITouch touch = touches.AnyObject as UITouch;

    if (touch != null) {
        latestPoint = touch.LocationInView (this);
        SetNeedsDisplay ();
    }
}

We call SetNeedsDisplay each time touches move in order for Draw to be called on the next run loop pass.

We’ll add lines to the path in the Draw method and use a red, dashed line to draw with. Implement Draw with the code shown below:

public override void Draw (System.Drawing.RectangleF rect)
{
    base.Draw (rect);

    if (!initialPoint.IsEmpty) {
        //get graphics context
        using(CGContext g = UIGraphics.GetCurrentContext ()){

            //set up drawing attributes
            g.SetLineWidth (2);
            UIColor.Red.SetStroke ();

            //add lines to the touch points
            if (path.IsEmpty) {
                path.AddLines (new PointF[]{initialPoint, latestPoint});
            } else {
                path.AddLineToPoint (latestPoint);
            }

            //use a dashed line
            g.SetLineDash (0, new float[]{5, 2});

            //add geometry to graphics context and draw it
                    g.AddPath (path);
            g.DrawPath (CGPathDrawingMode.Stroke);
        }
    }
}

If we run the application now, we can touch to draw on the screen, as shown in the following screenshot:

Images/01_path.png

Animating Along a Path

Next, let’s add the code to animate a layer along the drawn path.

Add a CALayer variable to the class and create it in the constructor:

CALayer layer;

public DemoView ()
{
    BackgroundColor = UIColor.White;

    path = new CGPath ();

    //create layer
    layer = new CALayer ();
    layer.Bounds = new RectangleF (0, 0, 50, 50);
    layer.Position = new PointF (50, 50);
    layer.Contents = UIImage.FromFile ("monkey.png").CGImage;
    layer.ContentsGravity = CALayer.GravityResizeAspect;
    layer.BorderWidth = 1.5f;
    layer.CornerRadius = 5;
    layer.BorderColor = UIColor.Blue.CGColor;
    layer.BackgroundColor = UIColor.Purple.CGColor;
}

We’ll add the layer as a sublayer of the view’s layer when the user lifts up their finger from the screen. Then, we will create a keyframe animation using the path, animating the layer’s Position.

Add the following code to the TouchesEnded method to accomplish this:

public override void TouchesEnded (MonoTouch.Foundation.NSSet touches, UIEvent evt)
{
    base.TouchesEnded (touches, evt);

    //add layer with image and animate along path

    if (layer.SuperLayer == null)
        Layer.AddSublayer (layer);

    // create a keyframe animation for the position using the path
    layer.Position = latestPoint;
    CAKeyFrameAnimation animPosition = (CAKeyFrameAnimation)CAKeyFrameAnimation.FromKeyPath ("position");
    animPosition.Path = path;
    animPosition.Duration = 3;
    layer.AddAnimation (animPosition, "position");
}

Run the application now and after drawing, a layer with an image is added that travels along the drawn path:

Images/00_final_app.png

Summary

In this article, we stepped through an example that tied graphics and animation concepts together. First, we showed how to use Core Graphics to draw a path in a UIView in response to user touch. Then we showed how to use Core Animation to make an image travel along that path.