Click here to Skip to main content
Click here to Skip to main content

Animation Along a Path for Silverlight

By , 4 Mar 2009
 

Introduction

Silverlight provides a good animation foundation, but lacks a convenient method to animate an object along an arbitrary geometric path. Windows Presentation Foundation, which is a superset of Silverlight, provides the animation classes, DoubleAnimationUsingPath and PointAnimationUsingPath. With these classes, it is easy to animate an object along a geometric path. This article provides the equivalent animation classes for Silverlight. I suspect future versions of Silverlight will provide this functionality, but until then, the code provided here will do the job.

PathAnimPic.jpg

Background

Currently, Silverlight does not provide animation classes for animating an object along an arbitrary geometric path, but Silverlight does provide key frame animation classes. With the key frame animation classes, you specify beginning and ending values, and then the animation class uses interpolation to calculate all the values in between. A collection of key frames can be assembled together to describe a motion path, but manually building these key frames for each motion path is tedious.

To programmatically generate the key frames describing the motion path, a method to ‘flatten’ the geometric path is needed. Flattening basically means the geometry is described by a series of line segments. The figure below shows an example of a flattened Bezier segment. Once we have the flattened path, then we can easily build the key frames for the storyboard.

flattenedpath.PNG

About the Code

SolnPic.JPG

The heart of the code is contained in the ‘PathAnimation’ project. In this project, the abstract BaseAnimationUsingPath class defines a number of dependency properties to control the animation (see below). Notice that this class inherits form DependencyObject rather than a Silverlight animation class. This is because most of the animation classes in Silverlight are sealed, and not extendable like the WPF animation classes. This has implications for the usage of the DoubleAnimationUsingPath and PointAnimationUsingPath animation classes, like they cannot be added to a Storyboard! They can be added as a Resource or created in the code-behind (example provided in the demo app).

BaseClassPic.JPG

The other important project here is ‘PathGeometryHelper’. This project implements the path flattening routine. Charles Petzold developed a path flattening method in his article and gave permission to reuse the code. Charles’ method was written for WPF, and so it needed to be ported to Silverlight. In porting this code to Silverlight, more missing functionality was found. Namely, Silverlight lacks some methods in the Matrix class. Also, Silverlight has no Vector class. Equivalent functionality for these classes (and a few others) has been provided in the ‘MatrixMathHelpers’ project.

An important point to make about the flattening routine is the ‘Tolerance’ parameter. This parameter has been exposed all the way up to the path animation classes. Basically, this parameter controls the number of segments used to approximate the original geometry path. The tolerance value must be greater than zero. A smaller tolerance value will yield greater accuracy (i.e., more line segments), and a larger value will yield less accuracy (i.e., poorer approximation of the geometry path). It is not recommended to make the tolerance too small because this will cause more key frames to be added to the storyboard, slow down the animation, and use too much memory. Play with the demo app and see how adjusting the tolerance affects the accuracy, but be careful not to set the value too small!

Another important piece of code is contained in PathConverter.cs. Currently, Silverlight has no built-in functionality to convert the mini-language string into a PathGeometry, but thankfully, a converter has been provided and included here in PathConverter.cs. With this handy converter, we can feed the animation classes arbitrarily complicated geometries created with Blend or other tools.

Using the Code

Two classes have been provided to animate an object along a geometric path: DoubleAnimationUsingPath and PointAnimationUsingPath. Both share a number of common dependency properties. These properties are equivalent to the Silverlight provided animation properties, so they should be familiar:

  • BeginTime: The time when the animation should start
  • Duration: The duration/length of the animation
  • AutoReverse: Reverses the animation at end when true
  • FillBehavior: Holds the value at the end of the animation, or resets to the value before the animation started
  • RepeatBehavior: Number of times to repeat
  • PathGeometry: Specifies the geometry that the object will follow when animating
  • TargetProperty: The property to animate
  • Target: The name of the object to animate
  • Tolerance: Controls the accuracy of the path flattening; must be greater than zero; smaller values give more accuracy

In addition to the properties above, all of the standard animation methods: Begin, Stop, Pause, Resume, and Seek have been provided.

DoubleAnimationUsingPath will only animate object properties of type double (e.g., height, width, X, Y, etc.). This animation class has one additional dependency property: Source. The Source property specifies to use either the X or Y output value of the PathGeometry to drive the animation.

As discussed in the previous section, the animation classes provided here cannot be used in a Storyboard like other Silverlight animation classes. They can, though, be added as a Resource or created in the code-behind (see the demo app for an example).

History

  • 9th November, 2008: Initial post
  • 4th March, 2009: Code updates
    • Add Completed Event to Animation classes
    • Added Angle to DoubleAnimationUsingPath

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

lneir
Software Developer (Senior) Skype
United States United States
Member
I work in the Bay Area primarily developing software on the Windows platform using C++, .NET/C#, WPF, and Silverlight.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionEasing functionmemberThomas sebire26 Nov '12 - 5:16 
Thanks for that work, it's working really great, but I have a question : How could I apply an easing function to the whole Storyboard of a DoubleAnimationUsingPath object ?
AnswerRe: Easing functionmemberThomas sebire26 Nov '12 - 23:30 
Or another solution would be to add properties (which exist in the initial classes) like AccelerationRatio and DecelerationRatio, would you know how to do it please ? Thanks
NewsPort for Windows 8membersentropie23 Nov '12 - 6:38 
Hi!
 
Since I was looking for such animation for a Windows 8/Modern UI app, I came to this project. I just had to make a few changes (because of the Silverlight defines) and put a simple Win 8 app around it.
 
You can find it here: http://php-xhtml.de/pub/PathAnimation_Win8.zip[^]
GeneralRe: Port for Windows 8memberlneir25 Nov '12 - 6:11 
cool, thanks.
GeneralRe: Port for Windows 8memberThomas sebire26 Nov '12 - 2:47 
Thanks for your code, it's working as a breeze. But I would have a question : How could we make the animation according to the UIElement center and not its top-left corner ?
 
I can't find how to put a center offset, do you have an idea ?
GeneralMy vote of 5membersureshkumartvr24 Jul '12 - 22:21 
Nice article
BugfgdgdgdfgmemberMember 344411223 Aug '11 - 22:16 
fgdgdsgdgfg
GeneralAnother article on a similar topic (animations along arbitrary paths using Easing functionality)memberNick Polyak1 Feb '11 - 19:56 
Take a look at my variations on a similar topic
Silverlight Animations along Arbitrary Mathematical Paths via Easing
Nick Polyak

GeneralI need code or instructions to animate object along a pathmemberzameer211 Apr '10 - 13:09 
I need code or instructions to animate object along a path
Generaltestmemberrahul jain23 Oct '09 - 14:48 
test
 
rahul

QuestionArcs flattening problemmemberMember 94717921 Sep '09 - 4:55 
Hi!
 
Great example, thanks! But there is some problem with Arc geometries. I'm getting NAN value here, because of the negative argument of the sqrt:
double centerDistance = Math.Sqrt(radiusY * radiusY - halfChord * halfChord);
 
any ideas on how to fix it?
 
Thanks again,
Vlad
AnswerRe: Arcs flattening problemmemberlneir21 Sep '09 - 17:59 
See discussion about Flattern Arc in messages here: Text on A Path for Silverlight[^]
GeneralSilverlight 3memberjboggs7710 May '09 - 12:38 
Has any of this changed with the GPU tie-in for Silverlight 3?
GeneralRe: Silverlight 3memberlneir25 May '09 - 14:33 
Good qustion, I don't believe so but would check on forums page here at code project or on silverlight.net for a more definitive answer.
 
Lynn
GeneralI added some feature (Angluar Animation)memberWon Dong2 Mar '09 - 11:26 
It's great for me to implement pathanimation, but I need rotating animation as well as translate animation.
I added some codes to your work both sample and class.
here to download Smile | :)
You can update your article if you want.
GeneralRe: I added some feature (Angluar Animation)memberlneir2 Mar '09 - 18:24 
Looks great...soon as I get some time I'll integrate the changes and post an update. Thanks.
GeneralCompleted Eventmemberdahlbyk11 Dec '08 - 15:59 
Great solution! Adding a Completed event is trivial and quite handy:
 
In BaseAnimationUsingPath.cs:
public event EventHandler Completed;
protected virtual void OnCompleted(EventArgs e)
{
    if (Completed != null)
        Completed(this, e);
}
In PointAnimationUsingPath.cs and DoubleAnimationUsingPath.cs, after Story is initialized in CreateStory():
Story.Completed += delegate(object sender, EventArgs e)
{
    OnCompleted(e);
};
You might also want to implement INotifyPropertyChanged (you're really close already) to make data binding easier. I discuss one strategy here: http://solutionizing.net/2008/10/24/inotifypropertychanged-dependency-properties-for-silverlight-pathtextblock/
 
Cheers ~
Keith
GeneralRe: Completed Eventmemberlneir3 Mar '09 - 18:46 
thanks...I've submitted an update with the completed event.
QuestionExcellent! One questionmemberGiancarlo Aguilera4 Dec '08 - 13:01 
First and foremost, this is a great piece of work!
 
One question/suggestion, why is that you decided not to derive from Timeline and instead derived from DO? I ask because ideally, in my humble opinion, it would be great if these path animations could be added to a storyboard object just like any other native animation. I guess it still could as is with something like myStoryBoard.Children.Add(myPathAnimation.Story) but I think I would have to tweak the code because the Story is null until Begin in invoked.
 
Great work!
AnswerRe: Excellent! One questionmemberlneir4 Dec '08 - 13:23 
Thanks for the feedback.
 
I briefly mentioned in article that in Silverlight you can not extend the Animation classes in Silverlight like you can in WPF. Currently, in Silverlight most of these classes are sealed or they provide no methods to override. I am hoping in future versions of Silverlight they will open the animation classes and make them extensible like WPF.
 
Lynn
GeneralIncreasing the speed of the animationmemberMember 12327883 Dec '08 - 5:05 
Speed of the animation different, how to do ? Set a new Property ?
GeneralRe: Increasing the speed of the animationmemberlneir3 Dec '08 - 6:15 
The SpeedRatio parameter is not currently exposed but could easily be added. You can add another dependency property to the class 'BaseAnimationUsingPath' that exposes the property. Just follow the pattern of the other DPs in this class that expose the various storyboard/timeline properties.
 
Lynn
GeneralExcellentmemberMohammad Dayyan26 Nov '08 - 9:07 
Hi lneir.
this is an excellent work.
5 from me
GeneralPath animation under silverlightmemberMember 400336711 Nov '08 - 8:05 
Hi Sir,
 
Just to let you that the purpose download of your article is the right one. After downloaded no way to find the functions that you describe in the articles. Can you send me the rigth folder please.
 
Thanks
 
Joel KPOHIHEIN
 
babatounde

GeneralRe: Path animation under silverlightmemberlneir11 Nov '08 - 8:12 
Open the solution file in Visual Studio. You should see all the projects in the article mentioned there. The animation classes are in the 'PathAnimation' project.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web01 | 2.6.130523.1 | Last Updated 4 Mar 2009
Article Copyright 2008 by lneir
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid