Convert a Rectangle into a RectangleF and vice versa in C#

[rectangle]

The RectangleF structure has an overloaded assignment operator = that lets you simply set a RectangleF equal to a Rectangle, so converting a Rectangle into a RectangleF is easy.

That makes sense because converting from Rectangle to RectangleF is a widening conversion. The integer values that define a Rectangle can be placed within float values without losing any precision.

Converting a RectangleF to a Rectangle is only slightly harder. The RectangleF class provides two methods, Round and Truncate, that perform this conversion.

This is a narrowing conversion because the float values that define the RectangleF don’t necessarily fit in the Rectangle structure’s integer properties.

This example uses the following code to convert a Rectangle into a RectangleF and back, and draw to all three rectangles.

private void Form1_Paint(object sender, PaintEventArgs e)
{
    // Make a rectangle.
    Rectangle rect1 = new Rectangle(20, 20,
        this.ClientSize.Width - 40,
        this.ClientSize.Height - 40);

    // Convert to RectangleF.
    RectangleF rectf = rect1;

    // Convert back to Rectangle.
    Rectangle rect2 = Rectangle.Round(rectf);
    //Rectangle rect2 = Rectangle.Truncate(rectf);

    // Draw them.
    using (Pen the_pen = new Pen(Color.Red, 20))
    {
        e.Graphics.DrawRectangle(the_pen, rect1);

        the_pen.Color = Color.Lime;
        the_pen.Width=10;
        e.Graphics.DrawRectangle(the_pen,
            rectf.X, rectf.Y, rectf.Width, rectf.Height);

        the_pen.Color = Color.Blue;
        the_pen.Width = 1;
        e.Graphics.DrawRectangle(the_pen, rect2);
    }
}

The code first defines a Rectangle. It uses assignment to convert it into a RectangleF and then uses the RectangleF structure’s Round method to convert it back into a Rectangle. The program then draws all three rectangles on top of each other with different line widths and colors so you can see them all.


Download Example   Follow me on Twitter   RSS feed   Donate




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

Leave a Reply

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