invizion invizion - 25 days ago 11
C# Question

Get the bounding rectangle of multiple rectangles

I have up to 4 rectangles on an image, for each of these rectangles I know their top left X,Y coordinate and their width,height. I want to create an Int32Rect with dimensions from most top left rectangle to the most bottom right rectangle. The main issue is that you can only create a System.Windows.Int32Rect with x,y,width,height parameters. Any ideas how I can accomplish this with my currently known values?

Trying to clarify, I want to create a Int32Rect that is the dimensions of all other "rectangles" on my image. So one large Int32Rect that starts from the "rectangle" at the top-left portion of the image and stretches to the "rectangle" that is at the bottom-right portion of the image.

Here's some code that does this for a single rectangle:

var topLeftOfBox = new Point(centerOfBoxRelativeToImage.X - Box.Width/2,
centerOfBoxRelativeToImage.Y - Box.Height/2);
return new CroppedBitmap(originalBitmap, new Int32Rect(topLeftOfBox.X, topLeftOfBox.Y, Box.Width, Box.Height));

Thanks for the help and ideas everyone, I found Aybe's answer to work the best for me.

Answer Source

You need to grab x/y mins/maxs for each rectangle and build a rectangle out of these values:

using System.Linq;
using System.Windows;

internal class Class1
    public Class1()
        var rect1 = new Int32Rect(10, 10, 10, 10);
        var rect2 = new Int32Rect(30, 30, 10, 10);
        var rect3 = new Int32Rect(50, 50, 10, 10);
        var rect4 = new Int32Rect(70, 70, 10, 10);

        var int32Rects = new[] { rect1, rect2, rect3, rect4 };
        var int32Rect = GetValue(int32Rects);

    private static Int32Rect GetValue(Int32Rect[] int32Rects)
        int xMin = int32Rects.Min(s => s.X);
        int yMin = int32Rects.Min(s => s.Y);
        int xMax = int32Rects.Max(s => s.X + s.Width);
        int yMax = int32Rects.Max(s => s.Y + s.Height);
        var int32Rect = new Int32Rect(xMin, yMin, xMax - xMin, yMax - yMin);
        return int32Rect;