Drawing a Polygon in GDI+ using VB.NET

In this article I will explain how to draw a Polygon in GDI+.
  • 4588
 
 

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


Imports System
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Data
Imports System.Drawing
Imports System.Linq
Imports System.Text
Imports System.Windows.Forms
Public Class Form1

    Private Sub Form1_Paint(ByVal sender As System.Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles MyBase.Paint
        Dim g As Graphics = e.Graphics

         ' Create a pen
        Dim greenPen As New Pen(Color.Green, 2)
        Dim redPen As New Pen(Color.Red, 2)

        ' Create points for polygon
        Dim pt1 As New PointF(40.0F, 50.0F)
        Dim pt2 As New PointF(60.0F, 70.0F)
        Dim pt3 As New PointF(80.0F, 34.0F)
        Dim pt4 As New PointF(120.0F, 180.0F)
        Dim pt5 As New PointF(200.0F, 150.0F)
        Dim ptsArray As PointF() = {pt1, pt2, pt3, pt4, pt5}

        ' Draw polygon
        e.Graphics.DrawPolygon(greenPen, ptsArray)

        ' Dispose of object
        greenPen.Dispose()
        redPen.Dispose()
    End Sub
End Class

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.

 

Categories

More Articles

© 2020 DotNetHeaven. All rights reserved.