Drawing Rectangles GDI+ using VB.NET

In this article I will explain you how to draw rectangles in GDI+.
  • 4108

The basic drawing object is a rectangle. When you draw a rectangle through your applications, you need to specify only the starting point, height and width of the rectangle. GDI+ takes care of the rest.

The Graphics class provides the DrawRectangle method, which draws a rectangle specified by a starting point, a width, and a height. The Graphics class also provides the DrawRectangles method, which draws a series of rectangles specified by an array of Rectangle structures.

To draw a rectangle, an application first creates a pen and a rectangle (location, width, and height), and then it calls DrawRectangle. Listing 3.3 draws rectangles using the different overloaded forms of DrawRectangle.

LISTING 3.3: Using DrawRectangle to draw rectangles

    Private Sub Form1_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles MyBase.Paint
        ' Create pens and points
        Dim redPen As New Pen(Color.Red, 1)
        Dim bluePen As New Pen(Color.Blue, 2)
        Dim greenPen As New Pen(Color.Green, 3)
        Dim x As Single = 5.0F, y As Single = 5.0F
        Dim width As Single = 100.0F
        Dim height As Single = 200.0F
        ' Create a rectangle
        Dim rect As New Rectangle(20, 20, 80, 40)
        ' Draw rectangles
        e.Graphics.DrawRectangle(bluePen, x, y, width, height)
        e.Graphics.DrawRectangle(redPen, 60, 80, 140, 50)
        e.Graphics.DrawRectangle(greenPen, rect)
        ' Dispose of objects
    End Sub

Figure 3.3 shows the output from the Listing 3.3


FIGURE 3.3: Drawing individual rectangles

The DrawRectangles method draws a series of rectangles using a single pen. It is useful when you need to draw multiple rectangles using the same pen (if you need to draw multiple rectangles using different pens, you must use multiple calls to DrawRectangle). A single call to DrawRectangles is faster than multiple DrawRectangle calls. DrawRectangles takes two parameters- a pen and an array of Rectangle and RectangleF structures- as shown in Listing 3.4.

LISTING 3.4: Using DrawRectangle to draw a series of rectangles

        Dim greenPen As New Pen(Color.Green, 4)
        Dim rectArray As RectangleF() = {New RectangleF(5.0F, 5.0F, 100.0F, 200.0F), New RectangleF(20.0F, 20.0F, 80.0F, 40.0F), New RectangleF(60.0F, 80.0F, 140.0F, 50.0F)}

        e.Graphics.DrawRectangles(greenPen, rectArray)

Figure 3.4 shows the output from Listing 3.4. As you can see, it's easy to draw multiple rectangles using the DrawRectangles methods.


FIGURE 3.4: Drawing a series of rectangles


Hope the article would have helped you in understanding drawing rectangles. Read other articles on GDI+ on the website.


More Articles

© 2020 DotNetHeaven. All rights reserved.