Rectangle.Union(Rectangle, Rectangle) Method

Definition

Gets a Rectangle structure that contains the union of two Rectangle structures.

C#
public static System.Drawing.Rectangle Union(System.Drawing.Rectangle a, System.Drawing.Rectangle b);

Parameters

a
Rectangle

A rectangle to union.

b
Rectangle

A rectangle to union.

Returns

A Rectangle structure that bounds the union of the two Rectangle structures.

Examples

The following code example demonstrates how to use the Union method. This example is designed for use with a Windows Form. Paste this code into a form and call the ShowRectangleUnion method when handling the form's Paint event, passing e as PaintEventArgs.

C#
private void ShowRectangleUnion(PaintEventArgs e)
{

    // Declare two rectangles and draw them.
    Rectangle rectangle1 = new Rectangle(30, 40, 50, 100);
    Rectangle rectangle2 = new Rectangle(50, 60, 100, 60);
    e.Graphics.DrawRectangle(Pens.Sienna, rectangle1);
    e.Graphics.DrawRectangle(Pens.BlueViolet, rectangle2);

    // Declare a third rectangle as a union of the first two.
    Rectangle rectangle3 = Rectangle.Union(rectangle1, rectangle2);

    // Fill in the third rectangle in a semi-transparent color.
    Color transparentColor = Color.FromArgb(40, 135, 135, 255);
    e.Graphics.FillRectangle(new SolidBrush(transparentColor), rectangle3);
}

Remarks

When one of the two rectangles is empty, meaning all of its values are zero, the Union method returns a rectangle with a starting point of (0, 0), and the height and width of the non-empty rectangle. For example, if you have two rectangles: A = (0, 0; 0, 0) and B = (1, 1; 2, 2), then the union of A and B is (0, 0; 2, 2).

Applies to

Product Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1