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.
Figure 11. A Polygon
The CreateAPolygon method listed in Listing 10 draws the same rectangle in Figure 11 dynamically.
- privatevoid CreateAPolygon() {
-
- SolidColorBrush yellowBrush = newSolidColorBrush();
- yellowBrush.Color = Colors.Yellow;
- SolidColorBrush blackBrush = newSolidColorBrush();
- blackBrush.Color = Colors.Black;
-
- Polygon yellowPolygon = newPolygon();
- yellowPolygon.Stroke = blackBrush;
- yellowPolygon.Fill = yellowBrush;
- yellowPolygon.StrokeThickness = 4;
-
- 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 = newPointCollection();
- polygonPoints.Add(Point1);
- polygonPoints.Add(Point2);
- polygonPoints.Add(Point3);
- polygonPoints.Add(Point4);
-
- yellowPolygon.Points = polygonPoints;
-
- LayoutRoot.Children.Add(yellowPolygon);
- }
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:
- <Grid Name="LayoutRoot"/>