In Focus

Drawing Bezier Curve With PolyBezierSegment in XAML

The PolyBezierSegment object represents one or more Bezier curves in XAML and WPF.

The PolyBezierSegment object represents one or more Bezier curves. The Points property represents all the points for multiple Bezier curves. 

The following XAML code snippet sets the Points property of the PolyBezierSegment. 

<PolyBezierSegment Points="0,0 50,0 100,100 100,0 150,0 200,100" />     
         
A Path object is used to draw Bezier curves by setting a PathGeomerty as Path.Data. The following code snippet creates a Path and sets a PolyBezierSegment as a part of PathFigure.Segments.

<Path Stroke="Blue" StrokeThickness="2" >
    <Path.Data>
        <PathGeometry>
            <PathGeometry.Figures>
                <PathFigureCollection>
                    <PathFigure StartPoint="10,100">
                        <PathFigure.Segments>
                            <PathSegmentCollection>
                                <PolyBezierSegment Points="0,0 50,0 100,100 100,0 150,0 200,100" />                                             
                            </PathSegmentCollection>
                        </PathFigure.Segments>
                    </PathFigure>
                </PathFigureCollection>
            </PathGeometry.Figures>
        </PathGeometry>
    </Path.Data>
</Path>

The output looks like Figure 1. 
PolyBezierSegment1.jpg
Figure 1

We can paint a Bezier curve by simply painting the path using the Fill method. The following code snippet was changed from the previous code so that it fills a path. 

<Path Stroke="Blue" StrokeThickness="2" Fill="Yellow" >

The new output looks like Figure 2. 

PolyBezierSegment2.jpg
Figure 2

The following code snippet dynamically creates the poly Bezier segment shown in Figure 2.

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

    PolyBezierSegment pbzSeg = new PolyBezierSegment();
    pbzSeg.Points.Add(new Point(0, 0));
    pbzSeg.Points.Add(new Point(50, 0));
    pbzSeg.Points.Add(new Point(100, 100));
    pbzSeg.Points.Add(new Point(100, 0));
    pbzSeg.Points.Add(new Point(150, 0));
    pbzSeg.Points.Add(new Point(200, 100));


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

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