VB.NET 1.1 Tutorial - GDI+ - Part 4 - RectanglesIn this part we will look at some simple applications that utilise the methods DrawRectangle and FillRectangle. Drawing RectanglesThere are two methods of drawing a rectangle. The first two versions of the DrawRectangle method takes five parameters. The syntax for the method definition is: Public Sub DrawRectangle( _ ByVal pen As Pen, _ ByVal x As Integer, _ ByVal y As Integer, _ ByVal width As Integer, _ ByVal height As Integer _ ) or Public Sub DrawRectangle( _ ByVal pen As Pen, _ ByVal x As Single, _ ByVal y As Single, _ ByVal width As Single, _ ByVal height As Single _ ) Where the Parameters are:
These methods draw a rectangle specified by a coordinate pair, a width, and a height. We will create a simple example to draw a rectangle on the form. Private Sub RectangleDemo_Paint( ByVal sender As Object, _
ByVal e As PaintEventArgs) _
Handles MyBase.Paint
' Get Graphics Object
Dim g As Graphics = e.Graphics
' Create Pen
Dim myPen As New Pen( Color.Blue, 2 )
' Draw rectangle to screen
g.DrawRectangle( myPen, 10, 10, 220, 150 )
' Now tidy up
myPen.Dispose()
End Sub
This code gives the following output: ![]() You can download the file rect01.vb from the link, or you can download my copy of the executable from here. Rectangles using RectangleThe other method uses a Rectangle structure to draw a rectangle. So to create the same rectangle as before, the code would like this. Private Sub RectangleDemo_Paint( ByVal sender As Object, _
ByVal e As PaintEventArgs) _
Handles MyBase.Paint
' Get Graphics Object
Dim g As Graphics = e.Graphics
' Create Pen
Dim myPen As New Pen( Color.Blue, 2 )
' Create rectangle
Dim rect As New Rectangle( 10, 10, 220, 150 )
' Draw rectangle to screen
g.DrawRectangle( myPen, rect )
' Now tidy up
myPen.Dispose()
End Sub
Filling RectanglesThe FillRectangle method is similar to the DrawRectangle method. There are essentially two ways of using the FillRectangle method. The first two versions take a brush and four integers or floating-point values. The other two versions take a brush and a Rectangle or RectangleF structure. Below is the code to draw a filled rectangle of the same size as before. Private Sub RectangleDemo_Paint( ByVal sender As Object, _
ByVal e As PaintEventArgs) _
Handles MyBase.Paint
' Get Graphics Object
Dim g As Graphics = e.Graphics
' Create Brush
Dim myBrush As New SolidBrush( Color.Blue )
' Draw rectangle to screen
g.FillRectangle( myBrush, 10, 10, 220, 150 )
' Now tidy up
myBrush.Dispose()
End Sub
![]() You can download the file rect02.vb from the link, or you can download my copy of the executable from here. ReferencesFor more information on the DrawRectangle Method, visit MSDN at microsoft here. For more information on the FillRectangle Method, visit MSDN at microsoft here. What Next?Next we will draw some simple Ellipses. Return to the Tutorial Contents. |