Blog Stats
  • Posts - 6
  • Articles - 0
  • Comments - 3
  • Trackbacks - 2

 

Animating a Polygon in WPF using PathGeometry

For a visualisation engine that I'm building I wanted to dynamically create polygons and animate them using WPF. I found out that there wasn't a lot of information about this out there on the web (only in XAML and not in code), so that's why I want to share this with you.

I am using a standard WPF project to demonstrate the animation. You need to add the System.Windows.Media.Animation namespace to the using statements. As you can see I am not using the Polygon type, because I haven't figured out how I can animate the Points inside a PointCollection . If anyone does know how to do this from code I would really like to hear it.

The code will create a PathGeometry consisting of LineSegments that have Points. The LineSegment's PointProperty will be animated.

Point pt1 = new Point(10, 10);
Point pt1to = new Point(100, 120);
Point pt2 = new Point(100, 10);
Point pt2to = new Point(150, 30);
Point pt3 = new Point(50, 50);
Point pt3to = new Point(30, 80);
PathGeometry pgeom = new PathGeometry();
PathFigure pfig1 = new PathFigure();

LineSegment ls1 = new LineSegment(pt1, true);
LineSegment ls2 = new LineSegment(pt2, true);
LineSegment ls3 = new LineSegment(pt3, true);

PointAnimation pa1 = new PointAnimation(pt1to, new Duration(new TimeSpan(0, 0, 4)));
PointAnimation pa2 = new PointAnimation(pt2to, new Duration(new TimeSpan(0, 0, 4)));
PointAnimation pa3 = new PointAnimation(pt3to, new Duration(new TimeSpan(0, 0, 4)));

pfig1.StartPoint = pt3;
pfig1.Segments.Add(ls1);
pfig1.Segments.Add(ls2);
pfig1.Segments.Add(ls3);

pgeom.Figures.Add(pfig1);
Path myPath = new Path();
myPath.Stroke =
Brushes.Black;
myPath.StrokeThickness = 3;
myPath.Fill =
Brushes.Blue;
myPath.Data = pgeom;

// Add this to the Grid I named 'MyGrid'
MyGrid.Children.Add(myPath);

ls1.BeginAnimation(LineSegment.PointProperty, pa1);
ls2.BeginAnimation(
LineSegment.PointProperty, pa2);
ls3.BeginAnimation(
LineSegment.PointProperty, pa3);
pfig1.BeginAnimation(
PathFigure.StartPointProperty, pa3);

Have fun with it!


Feedback

No comments posted yet.


Post a comment





 

Please add 2 and 7 and type the answer here:

 

 

Copyright © Robert-Jan Zandvoort