Add a DrawRectangle method to the Graphics class that takes a RectangleF as a parameter in C#

For some unknown reason, the Graphics class's DrawRectangle method cannot take a RectangleF as a parameter. It can take a Rectangle or four floats, 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.

public static class GraphicsExtensions
{
    // Draw a RectangleF.
    public static void DrawRectangle(this Graphics gr, Pen pen, RectangleF rectf)
    {
        gr.DrawRectangle(pen, rectf.Left, rectf.Top, rectf.Width, rectf.Height);
    }
}

Now the program can use the new version of the DrawRectangle method just as if it had been included in the original class. The following code shows how the example program draws its rectangle.

private void Form1_Paint(object sender, PaintEventArgs e)
{
    // Draw a rectangle.
    RectangleF rectf = new RectangleF(10, 10,
        ClientSize.Width - 20, ClientSize.Height - 20);
    e.Graphics.DrawRectangle(Pens.Red, rectf);            
}

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.