Draw PolyLine in WPF Using XAML PolyLineSegment

We can use the Polyline XAML element to draw lines in XAML and the Line class in WPF represents the XAML Line element. Learn here how to draw a Polyline in WPF. In this article, we will see how to use the PolyLineSegment to draw a line. 

Besides drawing lines using the Polyline element, we can also use the PolyLineSegment element. The PolyLineSegment is useful when a line becomes a part of a graphics path or a larger geometric object. 

The PolyLineSegment object represents a polyline. A polyline is a collection of connected straight lines. The Polyline object represents a polyline shape and draws a polyline with the given points. The Points property represents the points in a polyline.

The following code snippet creates a polyline segment.

<PolyLineSegment Points="10,100 100,200 200,30 250,200 200,150" />

A Path object is used to draw an arc by setting a PathGeomerty as Path.Data. The following code snippet creates a Path and sets a PolyLineSegment as a part of PathFigure.Segments.

<Path Stroke="Black" StrokeThickness="1">
                    <PathFigure StartPoint="0,100">
Points="10,100 100,200 200,30 250,200 200,150" />

The output looks like Figure 1.

Figure 1

We can paint a Polyline by simply painting the path using the Fill method. The following code snippet change in the previous code fills a path. It is actually filling the path, not the Polyline.

<Path Stroke="Black" StrokeThickness="1" Fill="Yellow"> 

The new output looks like Figure 2.


Figure 2

The following code snippet dynamically creates a polyine segments as shown in Figure 2. 

private void CreatePolyLineSegment()
    PathFigure pthFigure = new PathFigure();
    pthFigure.StartPoint = new Point(10, 100);

    System.Windows.Point Point1 = new System.Windows.Point(10, 100);
    System.Windows.Point Point2 = new System.Windows.Point(100, 200);
    System.Windows.Point Point3 = new System.Windows.Point(200, 30);
    System.Windows.Point Point4 = new System.Windows.Point(250, 200);
    System.Windows.Point Point5 = new System.Windows.Point(200, 150); 

    PolyLineSegment plineSeg = new PolyLineSegment();

    PathSegmentCollection myPathSegmentCollection = new PathSegmentCollection();

    pthFigure.Segments = myPathSegmentCollection; 

    PathFigureCollection pthFigureCollection = new PathFigureCollection();


    PathGeometry pthGeometry = new PathGeometry();

    pthGeometry.Figures = pthFigureCollection; 

    Path arcPath = new Path();

    arcPath.Stroke = new SolidColorBrush(Colors.Black);

    arcPath.StrokeThickness = 1;

    arcPath.Data = pthGeometry;

    arcPath.Fill = new SolidColorBrush(Colors.Yellow); 



Recommended Free Ebook
Similar Articles
Founded in 2003, Mindcracker is the authority in custom software development and innovation. We put best practices into action. We deliver solutions based on consumer and industry analysis.