A Marching Ants Animation for Universal Windows Apps

ants-line In a lot of apps we need to draw lines on some kind of map to display a route. If you want such line to also indicate the driving direction and speed, then you could apply the Marching Ants Effect, where you represent the route as a dotted or dashed line and let the dashes walk slowly sideways and up and down. In the XAML world, this is remarkably easy. All you need to do is apply a dash pattern to the line (or PolyLine, or any other Shape) through the Shape.StrokeDashArray property and then animate its Shape.StrokeDashOffset. Here’s an example of the effect – since a screenshot would be rather silly, I created a movie where you see the marching ants (well, in this case they might be orcs) in the attached sample project: MarchingAnts.wmv (1.4MB)

As mentioned, you have to first make the line look as an ants line, so use the appropriate values for the Shape.StrokeDashCap and Shape.StrokeLineJoin properties:

Polyline line = new Polyline();

// Add Points
// line.Points.Add(new Point(...));

line.Stroke = new SolidColorBrush(Colors.OrangeRed);
line.StrokeThickness = 18;
line.StrokeDashArray = new DoubleCollection() { 4, 2 };
line.StrokeDashCap = PenLineCap.Round;
line.StrokeLineJoin = PenLineJoin.Round;

For the animation I use a Storyboard with nothing but a DoubleAnimation on the Shape.StrokeDashOffset property. That offset moves from 0 to the total length of the dash pattern, which can be conveniently calculated with a LINQ Sum operator. I implemented it as an extension method to the Shape class. It only takes the duration of the animation as a parameter:

public static void ApplyMarchingAntsAnimation(this Shape shape, TimeSpan duration)
{
    Storyboard storyboard = new Storyboard();
    DoubleAnimation doubleAnimation = new DoubleAnimation();
    doubleAnimation.From = 0.0;
    doubleAnimation.To = -shape.StrokeDashArray.Sum();
    doubleAnimation.Duration = new Duration(duration);
    doubleAnimation.AutoReverse = false;
    doubleAnimation.RepeatBehavior = RepeatBehavior.Forever;
    doubleAnimation.EnableDependentAnimation = true; // Don't forget
    storyboard.Children.Add(doubleAnimation);
    Storyboard.SetTarget(doubleAnimation, shape);
    Storyboard.SetTargetProperty(doubleAnimation, "StrokeDashOffset");
    storyboard.Begin();
}

You can apply the animation to the Stroke of any Shape with the following one-liner:

line.ApplyMarchingAntsAnimation(TimeSpan.FromSeconds(1));

Everything is implemented in the shared part of a universal app, so it works on the desktop, the tablet and the phone too. This is just a screenshot, but I assure you “it’s alive…”:

MarchingAntsScreens

Here’s the whole source, it was written in Visual Studio 2013 Update 2: U2UC.WinUni.MarchingAnts.zip (555.9KB)

Enjoy!

XAML Brewer