Search code examples
c#pathgeometry

Building a PathGeometry from list of points without tons of other class creation


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;

Solution

  • 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));