|
|
Title | Add a DrawRectangle method to the Graphics class that takes a RectangleF as a parameter in Visual Basic .NET |
Description | This example shows how to add a DrawRectangle method to the Graphics class that takes a RectangleF as a parameter in Visual Basic .NET. |
Keywords | extension methods, Graphics class, graphics, DrawRectangle, example, example program, Windows Forms programming, Visual Basic .NET, VB.NET |
Categories | Software Engineering, Graphics |
|
|
For some unknown reason, the Graphics class's DrawRectangle method cannot take a RectangleF as a parameter. It can take a Rectangle or four Singles, and the FillRectangle method can take a RectangleF as a parameter, but the DrawRectangle method cannot.
Fortunately it's easy to add this as an overloaded version of the method by creating an extension method for the Graphics class. The following code shows how the example program does this.
|
|
Imports System.Runtime.CompilerServices
Module GraphicsExtensions
' Draw a RectangleF.
<Extension()> _
Public Sub DrawRectangle(ByVal gr As Graphics, ByVal _
the_pen As Pen, ByVal rectf As RectangleF)
gr.DrawRectangle(the_pen, rectf.Left, rectf.Top, _
rectf.Width, rectf.Height)
End Sub
End Module
|
|
Now the program can use the new version of the DrawRectangle method just as if it had been included in the original Graphics class. The following code shows how the example program draws its rectangle.
|
|
Private Sub Form1_Paint(ByVal sender As Object, ByVal e As _
System.Windows.Forms.PaintEventArgs) Handles Me.Paint
' Draw a rectangle.
Dim rectf As New RectangleF(10, 10, _
ClientSize.Width - 20, ClientSize.Height - 20)
e.Graphics.DrawRectangle(Pens.Red, rectf)
End Sub
|
|
|
|
|
|
|
|
|