Make rectangle extension methods in C#

[rectangle extension methods]

This example shows how to add rectangle extension methods to the Rectangle and RectangleF structs.

The Rectangle and RectangleF structs have several useful properties for determining their geometry such as Left, Right, Top, and Bottom, but they have no midpoint properties. The following code adds MidX and MidY methods to these structs so your code can easily find midpoint values.

public static class RectangleExtensions
{
    public static int MidX(this Rectangle rect)
    {
        return rect.Left + rect.Width / 2;
    }
    public static int MidY(this Rectangle rect)
    {
        return rect.Top + rect.Height / 2;
    }
    public static Point Center(this Rectangle rect)
    {
        return new Point(rect.MidX(), rect.MidY());
    }

    public static float MidX(this RectangleF rect)
    {
        return rect.Left + rect.Width / 2;
    }
    public static float MidY(this RectangleF rect)
    {
        return rect.Top + rect.Height / 2;
    }
    public static PointF Center(this RectangleF rect)
    {
        return new PointF(rect.MidX(), rect.MidY());
    }
}

These methods are contained in the static RectangleExtensions class. They simply calculate the X and Y midpoint coordinates and return them. The Center methods return Point and PointF values giving the rectangles’ centers.

You could easily perform these calculations when you need them, but putting them in extension methods makes them a little easier to use and makes your code easier to read. The following code shows how the program’s Paint event handler draws the shapes shown in the picture.

private void Form1_Paint(object sender, PaintEventArgs e)
{
    e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;

    Rectangle rect = new Rectangle(10, 10,
        ClientSize.Width - 20, ClientSize.Height - 20);
    e.Graphics.DrawRectangle(Pens.Red, rect);

    PointF[] points = 
    {
        new PointF(rect.MidX(), rect.Y),
        new PointF(rect.Right, rect.MidY()),
        new PointF(rect.MidX(), rect.Bottom),
        new PointF(rect.Left, rect.MidY()),
    };
    e.Graphics.DrawPolygon(Pens.Blue, points);

    e.Graphics.DrawLine(Pens.Green,
        rect.Center(), new PointF(0, 0));
}

The code creates a RectangleF struct and draws it. It then uses the struct’s MidX, MidY, and Center extension methods to draw the blue diamond and the green line.


Download Example   Follow me on Twitter   RSS feed   Donate




This entry was posted in drawing, extension methods, graphics and tagged , , , , , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *