Polygon in WPF


A polygon is a series of connected lines which is a closed shape. A closed shape is a shape that has same start point and end point.

The Polygon object represents a polygon shape and draws a polygon for the given connected points. The Fill property fills the interior of an ellipse. The Stroke property sets the color and StrokeThickness represents the width of the outer line of an ellipse. The Points property of the Polygon represents a collection of Point that defines the points in a polygon. The FillRule property represents how the interior of the polygon is determined.

Creating a Polygon

The Polygon element in XAML creates a polygon shape. The following code snippet creates a polygon by setting its Points property to the connected points in a polygon. The code also sets the black stroke of width 4 and fills it with yellow color. 

<Polygon Points="50, 100 200, 100 200, 200 300, 30"

    Stroke="Black" StrokeThickness="4"

         Fill="Yellow" />

 

The output looks like Figure 11.

  

PolygonImg.gif

Figure 11. A Polygon

The CreateAPolygon method listed in Listing 10 draws same rectangle in Figure 11 dynamically.

private void CreateAPolygon()

 {

     // Create a blue and a black Brush

     SolidColorBrush yellowBrush = new SolidColorBrush();

     yellowBrush.Color = Colors.Yellow;

     SolidColorBrush blackBrush = new SolidColorBrush();

     blackBrush.Color = Colors.Black;

 

     // Create a Polygon

     Polygon yellowPolygon = new Polygon();

     yellowPolygon.Stroke = blackBrush;

     yellowPolygon.Fill = yellowBrush;

     yellowPolygon.StrokeThickness = 4;

  

     // Create a collection of points for a polygon

     System.Windows.Point Point1 = new System.Windows.Point(50, 100);

     System.Windows.Point Point2 = new System.Windows.Point(200, 100);

     System.Windows.Point Point3 = new System.Windows.Point(200, 200);

     System.Windows.Point Point4 = new System.Windows.Point(300, 30);

     PointCollection polygonPoints = new PointCollection();

     polygonPoints.Add(Point1);

     polygonPoints.Add(Point2);

     polygonPoints.Add(Point3);

     polygonPoints.Add(Point4);

 

     // Set Polygon.Points properties

     yellowPolygon.Points = polygonPoints;

 

     // Add Polygon to the page

     LayoutRoot.Children.Add(yellowPolygon);

 }

Listing 10


LayoutRoot in the this code below code is the name (ID) of the parent Grid panel. By default, a Grid does not have Name attribute set. You must set it using the following code:

<Grid Name="LayoutRoot"

/>



erver'>
Up Next
    Ebook Download
    View all
    Learn
    View all