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. 

  1. <Polygon Points="50, 100 200, 100 200, 200 300, 30" Stroke="Black" StrokeThickness="4" Fill="Yellow" />  

The output looks like Figure 11.

A Polygon
Figure 11. A Polygon

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

  1. privatevoid CreateAPolygon() {  
  2.     // Create a blue and a black Brush  
  3.     SolidColorBrush yellowBrush = newSolidColorBrush();  
  4.     yellowBrush.Color = Colors.Yellow;  
  5.     SolidColorBrush blackBrush = newSolidColorBrush();  
  6.     blackBrush.Color = Colors.Black;  
  7.     // Create a Polygon  
  8.     Polygon yellowPolygon = newPolygon();  
  9.     yellowPolygon.Stroke = blackBrush;  
  10.     yellowPolygon.Fill = yellowBrush;  
  11.     yellowPolygon.StrokeThickness = 4;  
  12.     // Create a collection of points for a polygon  
  13.     System.Windows.Point Point1 = new System.Windows.Point(50, 100);  
  14.     System.Windows.Point Point2 = new System.Windows.Point(200, 100);  
  15.     System.Windows.Point Point3 = new System.Windows.Point(200, 200);  
  16.     System.Windows.Point Point4 = new System.Windows.Point(300, 30);  
  17.     PointCollection polygonPoints = newPointCollection();  
  18.     polygonPoints.Add(Point1);  
  19.     polygonPoints.Add(Point2);  
  20.     polygonPoints.Add(Point3);  
  21.     polygonPoints.Add(Point4);  
  22.     // Set Polygon.Points properties  
  23.     yellowPolygon.Points = polygonPoints;  
  24.     // Add Polygon to the page  
  25.     LayoutRoot.Children.Add(yellowPolygon);  
  26. }  

Listing 10

LayoutRoot in the 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:

  1. <Grid Name="LayoutRoot"/>  

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.