Home

GDI+ Shapes: Rectangles and Squares

 

Description

 

A rectangle is a geometric figure made of four sides that compose four right angles. To draw a rectangle, you can either specify the Rectangle value that encloses it, or you can define its location and its dimensions. To draw a rectangle that is enclosed in a Rectangle value, you can use the following version of the Graphics.DrawRectangle() method:

Public Sub DrawRectangle(pen As Pen, rect As Rectangle)

Remember that such a rectangle object can be illustrated as follows:

Illustration: Rectangle

After defining a Rectangle variable, you can pass it to the method. Here is an example:

Imports System.Drawing
Imports System.Windows.Forms

Module Exercise

    Public Class Starter
        Inherits Form

        Dim components As System.ComponentModel.Container

        Public Sub New()
            InitializeComponent()
        End Sub

        Public Sub InitializeComponent()

        End Sub

        Private Sub FormPaint(ByVal sender As Object, _
                              ByVal e As PaintEventArgs) _
                              Handles MyBase.Paint

            Dim penCurrent As Pen = New Pen(Color.Red)
            Dim Rect As Rectangle = New Rectangle(20, 20, 248, 162)

            e.Graphics.DrawRectangle(penCurrent, Rect)

        End Sub
    End Class

    Function Main() As Integer

        Dim frmStart As Starter = New Starter

        Application.Run(frmStart)

        Return 0
    End Function

End Module

Remember that you can also define a Pen and/or a Rectangle objects in the parentheses of the method:

Private Sub FormPaint(ByVal sender As Object, _
                              ByVal e As PaintEventArgs) _
                              Handles MyBase.Paint

            Dim penCurrent As Pen = New Pen(Color.Red)
            Dim Rect As Rectangle = New Rectangle(20, 20, 248, 162)

            e.Graphics.DrawRectangle(New Pen(Color.Red), _
                   New Rectangle(20, 20, 248, 162))

End Sub

This would produce:

A Rectangle Drawn From a Rectangle Value

It is (very) important to remember that the third argument of the Rectangle represents its width (and not its right) value and the fourth argument represents its height (and not its bottom) value. This is a confusing fact for those who have programmed in GDI: GDI+ defines a Rectangle differently than GDI. In fact, to determine the location and dimensions of a rectangle to draw, the Graphics class provides the following versions of the DrawRectangle() method:

Public Sub DrawRectangle(pen As Pen, x As Integer, _
		          y As Integer, width As Integer, _
		          height As Integer)
Public Sub DrawRectangle(pen As Pen, x As Single, _
		          y As Single, width As Single, _
		          height As Single)

This time, the rectangle is represented by its location with a point at (x, y) and its dimensions with the width and height argument. This can be illustrated in a Windows coordinate system as follows:

Rectangle

Based on this, the earlier rectangle can also be drawn with the following:

Private Sub FormPaint(ByVal sender As Object, _
                              ByVal e As PaintEventArgs) _
                              Handles MyBase.Paint

            e.Graphics.DrawRectangle(New Pen(Color.Red), 20, 20, 248, 162)

End Sub

A square is a rectangle whose four sides are equal.

Practical LearningPractical Learning: Drawing a Rectangle

  1. Start Microsoft Visual Basic and create a new Windows Application named WeeklySales1
  2. Design the form as follows:
     
    Weekly Sales
    Control Name Text
    Label Label   Monday
    Label Label   Tuesday
    Label Label   Wednesday
    Label Label   Thursday
    Label Label   Friday
    TextBox TextBox txtMonday 0
    TextBox TextBox txtTuesday 0
    TextBox TextBox txtWednesday 0
    TextBox TextBox txtThursday 0
    TextBox TextBox txtFriday 0
    Button Button Generate btnGenerate
  3. Double-click an unoccupied area of the form and change the file as follows:
     
    Public Class Form1
    
        Private graphDrawingArea As Graphics
        Private bmpDrawingArea As Bitmap
    
        Private Sub Form1_Load(ByVal sender As System.Object, _
                               ByVal e As System.EventArgs) _
                               Handles MyBase.Load
            bmpDrawingArea = New Bitmap(Width, Height)
            graphDrawingArea = Graphics.FromImage(bmpDrawingArea)
        End Sub
    End Class
  4. In the Method Name combo box, select Paint and implement its event as follows:
     
    Private Sub Form1_Paint(ByVal sender As Object, _
                     ByVal e As System.Windows.Forms.PaintEventArgs) _
                            Handles Me.Paint
            e.Graphics.DrawImage(bmpDrawingArea, 0, 0)
    End Sub
  5. In the Class Name combo box, select btnGenerate
  6. In the Method Name combo box, select Click and implement the event as follows:
     
    Private Sub btnGenerate_Click(ByVal sender As Object, _
                                      ByVal e As System.EventArgs) _
                                      Handles btnGenerate.Click
            Dim monday As Integer
            Dim tuesday As Integer
            Dim wednesday As Integer
            Dim thursday As Integer
            Dim friday As Integer
    
            Try
                monday = CInt(txtMonday.Text) / 100
            Catch
                MsgBox("Invalid sales on Monday")
                txtMonday.Text = "0"
            End Try
    
            Try
                tuesday = CInt(txtTuesday.Text) / 100
            Catch
                MsgBox("Invalid sales on Tuesday")
                txtTuesday.Text = "0"
            End Try
    
            Try
                wednesday = Integer.Parse(txtWednesday.Text) / 100
            Catch
                MsgBox("Invalid sales on Wednesday")
                txtWednesday.Text = "0"
            End Try
    
            Try
                thursday = CInt(txtThursday.Text) / 100
            Catch
                MsgBox("Invalid sales on Thursday")
                txtThursday.Text = "0"
            End Try
    
            Try
                friday = CInt(txtFriday.Text) / 100
            Catch
                MsgBox("Invalid sales on Friday")
                txtFriday.Text = "0"
            End Try
    
            graphDrawingArea.Clear(BackColor)
    
            graphDrawingArea.DrawRectangle(New Pen(Color.Red), _
                                txtMonday.Left + 10, _
                                300 - monday, 40, monday)
            graphDrawingArea.DrawRectangle(New Pen(Color.Blue), _
                                txtTuesday.Left + 10, _
                                300 - tuesday, 40, tuesday)
            graphDrawingArea.DrawRectangle(New Pen(Color.Fuchsia), _
                                txtWednesday.Left + 5, _
                                300 - wednesday, 40, wednesday)
            graphDrawingArea.DrawRectangle(New Pen(Color.Brown), _
                                txtThursday.Left + 5, _
                                300 - thursday, 40, thursday)
            graphDrawingArea.DrawRectangle(New Pen(Color.Turquoise), _
                                txtFriday.Left + 5, _
                                300 - friday, 40, friday)
    
            graphDrawingArea.DrawRectangle(New Pen(Color.Black), _
                                10, 300, Width - 30, 1)
            Invalidate()
    End Sub
  7. Execute the application and test the form
     
     Weekly Sales
  8. After using it, close the form

A Series of Rectangles

The DrawRectangle() method is used to draw one rectangle. If you plan to draw many rectangles, you can proceed in one step by using the Graphics.DrawRectangles() method. It comes in two versions whose syntaxes are:

Public Sub DrawRectangles(pen As Pen, rects As Rectangle() )
Public Sub DrawRectangles(pen As Pen, rects As RectangleF())

This method requires an array of Rectangle or RectangleF values. When executed, it draws individual rectangles using each member of the array as its own rectangle. Here is an example:

Private Sub FormPaint(ByVal sender As Object, _
                              ByVal e As PaintEventArgs) _
                              Handles MyBase.Paint

            Dim penCurrent As Pen = New Pen(Color.Red)
            Dim Rect As Rectangle() =  _
			New Rectangle(20, 20, 120, 20), _
                                    	New Rectangle(20, 50, 120, 30), _
                     		New Rectangle(20, 90, 120, 40), _
                     		New Rectangle(20, 140, 120, 60)}

            e.Graphics.DrawRectangles(penCurrent, Rect)

End Sub

This would produce:

Rectangles

Practical LearningPractical Learning: Drawing a Series of Rectangles

  1. Start a new Windows Application named YearlySales1
  2. Design the form as follows:
     
    Yearly Sales
     
    Control Name Text
    GroupBox GroupBox   Current Year's Sales
    Label Label   1st Qtr
    Label Label   2nd Qtr
    Label Label   3rd Qtr
    Label Label   4th Qtr
    TextBox TextBox txtCurrentQtr1 0
    TextBox TextBox txtCurrentQtr2 0
    TextBox TextBox txtCurrentQtr3 0
    TextBox TextBox txtCurrentQtr4 0
    Button Button Close btnClose
    GroupBox GroupBox   Previous Year's Sales
    Label Label   1st Qtr
    Label Label   2nd Qtr
    Label Label   3rd Qtr
    Label Label   4th Qtr
    TextBox TextBox txtPreviousQtr1 0
    TextBox TextBox txtPreviousQtr2 0
    TextBox TextBox txtPreviousQtr3 0
    TextBox TextBox txtPreviousQtr4 0
    Button Button Generate btnGenerate
    Label Label   _________ Legend _________
    Label Label lblCurYear This Year's Sales
    Label Label lblLastYear Last Year's Sales
  3. Double-click an unoccupied area of the form and change the file as follows:
     
    Public Class Form1
    
        Private graphDrawingArea As Graphics
        Private bmpDrawingArea As Bitmap
    
        Private Sub Form1_Load(ByVal sender As System.Object, _
                               ByVal e As System.EventArgs) _
                               Handles MyBase.Load
            bmpDrawingArea = New Bitmap(Width, Height)
            graphDrawingArea = Graphics.FromImage(bmpDrawingArea)
        End Sub
    End Class
  4. In Method Name combo box, select Paint and implement its event as follows:
     
    Private Sub Form1_Paint(ByVal sender As Object, _
                                ByVal e As System.Windows.Forms.PaintEventArgs) _
                                Handles Me.Paint
            e.Graphics.DrawImage(bmpDrawingArea, 0, 0)
    End Sub
  5. In the Class Name combo box, select btnGenerate
  6. In the Method Name combo box, select Click and implement the event as follows:
     
    Private Sub btnGenerate_Click(ByVal sender As Object, _
                                      ByVal e As System.EventArgs) _
                                      Handles btnGenerate.Click
            Dim curQtr1 As Integer
            Dim curQtr2 As Integer
            Dim curQtr3 As Integer
            Dim curQtr4 As Integer
            Dim prvQtr1 As Integer
            Dim prvQtr2 As Integer
            Dim prvQtr3 As Integer
            Dim prvQtr4 As Integer
    
            ' Retrieve the values of the current year's sales
            Try
                curQtr1 = CInt(txtCurrentQtr1.Text) / 100
            Catch
                MsgBox("Invalid value for the first quater")
                curQtr1 = 0
            End Try
    
            Try
                curQtr2 = CInt(txtCurrentQtr2.Text) / 100
            Catch
                MsgBox("Invalid value for the second quater")
                curQtr2 = 0
            End Try
    
            Try
                curQtr3 = CInt(txtCurrentQtr3.Text) / 100
            Catch
                MsgBox("Invalid value for the third quater")
                curQtr3 = 0
            End Try
    
            Try
                curQtr4 = CInt(txtCurrentQtr4.Text) / 100
            Catch
                MsgBox("Invalid value for the fourth quater")
                curQtr4 = 0
            End Try
    
            ' Create an array of Rectangle objects for the current year
            Dim rectCurrentYear As Rectangle() = { _
                           New Rectangle(txtCurrentQtr1.Left + 20, _
                                      380 - curQtr1, 40, curQtr1), _
                           New Rectangle(txtCurrentQtr2.Left + 20, _
                                      380 - curQtr2, 40, curQtr2), _
                           New Rectangle(txtCurrentQtr3.Left + 20, _
                                      380 - curQtr3, 40, curQtr3), _
                           New Rectangle(txtCurrentQtr4.Left + 20, _
                                      380 - curQtr4, 40, curQtr4)}
    
            ' Retrieve the values of last year's sales
            Try
                prvQtr1 = CInt(txtPreviousQtr1.Text) / 100
            Catch
                MsgBox("Invalid value for the third quater")
                prvQtr1 = 0
            End Try
    
            Try
                prvQtr2 = CInt(txtPreviousQtr2.Text) / 100
            Catch
                MsgBox("Invalid value for the third quater")
                prvQtr2 = 0
            End Try
    
            Try
                prvQtr3 = CInt(txtPreviousQtr3.Text) / 100
            Catch
                MsgBox("Invalid value for the third quater")
                prvQtr3 = 0
            End Try
    
            Try
                prvQtr4 = CInt(txtPreviousQtr4.Text) / 100
            Catch
                MsgBox("Invalid value for the third quater")
                prvQtr4 = 0
            End Try
    
            ' Create an array of Rectangle objects for the previous year
            Dim rectPreviousYear As Rectangle() = { _
                           New Rectangle(txtPreviousQtr1.Left + 30, _
                                      380 - prvQtr1, 40, prvQtr1), _
                           New Rectangle(txtPreviousQtr2.Left + 30, _
                                      380 - prvQtr2, 40, prvQtr2), _
                           New Rectangle(txtPreviousQtr3.Left + 30, _
                                      380 - prvQtr3, 40, prvQtr3), _
                           New Rectangle(txtPreviousQtr4.Left + 30, _
                                      380 - prvQtr4, 40, prvQtr4)}
    
            ' In case the user has changed the values,
            ' erase the previous chart
            graphDrawingArea.Clear(BackColor)
    
            ' Draw the chart for the previous year first to send it back
            graphDrawingArea.DrawRectangles(New Pen(Color.Blue), _
                             rectPreviousYear)
            ' Draw the chart for the current year in front
            graphDrawingArea.DrawRectangles(New Pen(Color.Red), _
                             rectCurrentYear)
    
            ' Draw the small rectangles of the legend
            graphDrawingArea.DrawRectangle(New Pen(Color.Blue), _
                            lblCurYear.Left - 30, _
                            lblCurYear.Top, 14, 10)
            graphDrawingArea.DrawRectangle(New Pen(Color.Red), _
                            lblLastYear.Left - 30, _
                            lblLastYear.Top, 14, 10)
    
            graphDrawingArea.DrawRectangle(New Pen(Color.Black), _
                             25, 380, Width - 220, 1)
            Invalidate()
    End Sub
  7. In the Class Name combo box, select btnClose
  8. In the Method Name combo box, select Click and implement its event as follows:
     
    Private Sub btnClose_Click(ByVal sender As Object, _
                                   ByVal e As System.EventArgs) _
                                   Handles btnClose.Click
            End
    End Sub
  9. Execute the application and test the form
     
     Yearly Sales
  10. After using it, close the form

Download

 

Home Copyright © 2008-2012 FunctionX Home