1

I am trying to build a simple polygonal PathGeometry from a custom list of points. I found the following code on the msdn website, and it appears to work fine, with a simple modification to loop and add LineSegments, but it seems like an awful amount of inelegant mess to do what seems to be a relatively simple task. Is there a better way?

PathFigure myPathFigure = new PathFigure();
myPathFigure.StartPoint = new Point(10, 50);

LineSegment myLineSegment = new LineSegment();
myLineSegment.Point = new Point(200, 70);

PathSegmentCollection myPathSegmentCollection = new PathSegmentCollection();
myPathSegmentCollection.Add(myLineSegment);

myPathFigure.Segments = myPathSegmentCollection;

PathFigureCollection myPathFigureCollection = new PathFigureCollection();
myPathFigureCollection.Add(myPathFigure);

PathGeometry myPathGeometry = new PathGeometry();
myPathGeometry.Figures = myPathFigureCollection;

Path myPath = new Path();
myPath.Stroke = Brushes.Black;
myPath.StrokeThickness = 1;
myPath.Data = myPathGeometry;
fexam
  • 15
  • 4
  • I don't believe that there is a better way, but you could wrap it in a function (such as `Path makePath(Point[] points)`). – Jashaszun Jul 25 '14 at 15:12

1 Answers1

1

You can wrap it in a function, and you can also consolidate some statements.

Path makePath(params Point[] points)
{
    Path path = new Path()
    {
        Stroke = Brushes.Black,
        StrokeThickness = 1
    };
    if (points.Length == 0)
        return path;

    PathSegmentCollection pathSegments = new PathSegmentCollection();
    for (int i = 1; i < points.Length; i++)
        pathSegments.Add(new LineSegment(points[i], true));

    path.Data = new PathGeometry()
    {
        Figures = new PathFigureCollection()
        {
            new PathFigure()
            {
                StartPoint = points[0],
                Segments = pathSegments
            }
        }
    };
    return path;
}

Then you can call it like this:

Path myPath = makePath(new Point(10, 50), new Point(200, 70));
Jashaszun
  • 9,207
  • 3
  • 29
  • 57
  • Thanks, that works wonderfully! I modified it slightly to add a segment back to the start point, but that only matters if you are drawing it with some functions, as others don't seem to care. (Of course I didn't think to wrap it in a function. I obviously need more caffeine >.> ) – fexam Jul 25 '14 at 15:50