Draw Line in WPF Using XAML LineSegment

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


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

The LineSegment object represents a line between a start point and an end point. The LineSegment class has one property, Point that represents the end point of the line. The start point is a part of the path. 

The following XAML code snippet creates a line segment. A Path object is used to draw an arc by setting a PathGeomerty as Path.Data. 

<Path Stroke="Black" StrokeThickness="1">
    <Path.Data>
        <PathGeometry>
            <PathGeometry.Figures>
                <PathFigureCollection>
                    <PathFigure StartPoint="0,100">
                        <PathFigure.Segments>
                            <PathSegmentCollection>
                                <LineSegment Point="200,100" />
                            </PathSegmentCollection>
                        </PathFigure.Segments>
                    </PathFigure>
                </PathFigureCollection>
            </PathGeometry.Figures>
        </PathGeometry>
    </Path.Data>
</Path>


The following code snippet creates a Path and sets a LineSegment as a part of PathFigure.Segments. The output looks like Figure 1. 

LineSegment.jpg

Figure 1 

The following code snippet dynamically creates the line segment shown in Figure 1.

private void CreateLineSegment()
{
    PathFigure pthFigure = new PathFigure();
    pthFigure.StartPoint = new Point(10, 100);
    LineSegment lineSeg = new LineSegment ();
    lineSeg.Point = new Point(200, 100);  

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

    pthFigure.Segments = myPathSegmentCollection; 

    PathFigureCollection pthFigureCollection = new PathFigureCollection();
    pthFigureCollection.Add(pthFigure);
    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); 

    LayoutRoot.Children.Add(arcPath);

}

Up Next
    Ebook Download
    View all
    Learn
    View all