获取多个矩形的边界矩形

时间:2014-10-21 14:01:00

标签: c# rectangles

我在图像上最多有4个矩形,对于这些矩形中的每一个,我知道它们的左上角X,Y坐标及其宽度,高度。我想创建一个Int32Rect,其尺寸从最左上方的矩形到最右下方的矩形。主要问题是您只能使用x,y,width,height参数创建System.Windows.Int32Rect。有什么想法我如何用我目前已知的价值观来实现这一目标?

编辑: 试图澄清,我想创建一个Int32Rect,它是所有其他"矩形的尺寸"在我的形象。所以一个大的Int32Rect从"矩形开始#34;在图像的左上部分,并延伸到"矩形"这是在图像的右下部分。

以下是为单个矩形执行此操作的一些代码:

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));

感谢大家的帮助和想法,我发现Aybe的答案对我来说是最好的。

3 个答案:

答案 0 :(得分:2)

您需要为每个矩形抓取x / y分钟/最大值并使用这些值构建矩形:

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;
    }
}

结果:

{10,10,70,70}

答案 1 :(得分:0)

这个问题有点不清楚,所以我将首先阐述我对你所寻找的内容的理解。在我阅读你的问题时,你有一个矩形集合,并且正在寻找包含集合中所有矩形的最小矩形。

以下是您需要了解的信息:

  • rect的左上角是(X, Y),右下角是(X+Width, Y+Height)
  • 矩形的宽度由Right - Left给出。高度由Bottom - Top给出。

现在您可以在这些数量之间进行转换,其余部分很容易。找到最小顶值,最小左值,最大右值和最大底值。将这些值输入上面第二个项目符号中的方程式,然后就完成了。

答案 2 :(得分:0)

您可以节省一些精力,避免担心拥有"世界知识"其中Rectangle位于最底部/顶部。最左侧/最右侧:

public static class RectangleExtensions
{
    public static Rectangle RectsGetBounds(this Rectangle rect, params Rectangle[] rects)
    {
        Rectangle rbase = rect;

        for (int i = 0; i < rects.Length; i++)
        {
            rbase = Rectangle.Union(rbase, rects[i]);
        }

        return rbase;
    }

    public static Rectangle ControlsGetBounds(this Control cntrl, params Control[] cntrls)
    {
        return RectsGetBounds(cntrl.Bounds, cntrls.Select(c => c.Bounds).ToArray());
    }
}
相关问题