Drawing a Polygon in GDI+


This article has been excerpted from book "Graphics Programming with GDI+ ".

A polygon is a closed shape with three of more straight sides. Examples of polygons include triangles and rectangles.

The Graphics class provides a DrawPolygon method to draw polygons. DrawPolygon draws a polygon defined by an array of points. It takes two arguments: a pen and an array of Points or PointF structures.

To draw a polygon, an application first creates a pen and an array of points and then calls the DrawPolygon method with these parameters. Listing 3.19 draws a polygon with five points.

LISTING 3.19: Drawing a polygon


using
System;
using
System.Collections.Generic;
using
System.ComponentModel;
using
System.Data;
using
System.Drawing;
using
System.Linq;
using
System.Text;
using
System.Windows.Forms;

namespace
WindowsFormsApplication11
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Paint(object sender,
        System.Windows.Forms.PaintEventArgs e)
        {
            Graphics g = e.Graphics;

            // Create a pen
            Pen greenPen = new Pen(Color.Green, 2);
            Pen redPen = new Pen(Color.Red, 2);

            // Create points for polygon
            PointF pt1 = new PointF(40.0F, 50.0F);
            PointF pt2 = new PointF(60.0F, 70.0F);
            PointF pt3 = new PointF(80.0F, 34.0F);
            PointF pt4 = new PointF(120.0F, 180.0F);
            PointF pt5 = new PointF(200.0F, 150.0F);
            PointF[] ptsArray =
        {
              pt1, pt2, pt3, pt4, pt5
        };

            // Draw polygon
            e.Graphics.DrawPolygon(greenPen, ptsArray);

            // Dispose of object
            greenPen.Dispose();
            redPen.Dispose();
        }
    }
}


Figure 3.26 shows the output from Listing 3.19

3.26.gif

FIGURE 3.26: Drawing a polygon

Conclusion

Hope the article would have helped you in understanding how to draw a Polygon  in GDI+. Read other articles on GDI+ on the website.

bookGDI.jpg This book teaches .NET developers how to work with GDI+ as they develop applications that include graphics, or that interact with monitors or printers. It begins by explaining the difference between GDI and GDI+, and covering the basic concepts of graphics programming in Windows.


Similar Articles
Mindcracker
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.