如何获得重叠的矩形坐标

时间:2010-07-03 22:09:47

标签: c#

假设我有以下重叠矩形(“a”和“b”):

aaaaaaaa
aaaaccccbbbbb
aaaaccccbbbbb
aaaaccccbbbbb
    bbbbbbbbb
    bbbbbbbbb

我已经看到很多关于如何计算内部矩形(“c”)的区域的想法,但是我将如何获得实际的上/左/下/右坐标对吗?

5 个答案:

答案 0 :(得分:13)

答案 1 :(得分:9)

可以根据以下逻辑找到两个矩形的重叠区域的X坐标。

要找到Y坐标,请在四个假设的最后一个以及所有三个假设中用Y替换X.


<强>假设:

  • A B 是矩形(其边沿X轴和Y轴对齐),

  • 每个矩形由两个点定义( x min / y min ) - ( x max / y max

  • 其中 x min &lt; x max y min &lt; y max

  • A.x min &lt; B.x <子>分钟


案例1 - 无重叠:

+--------+
|A       |    
|        |    +----+
|        |    |B   |
|        |    +----+
|        |
+--------+

A.x min &lt; A.x max &lt; B.x min &lt; B.x max ⇒没有重叠。


案例2 - 有些重叠:

+--------+
|A       |
|     +--+-+
|     |B | |
|     +--+-+
|        |
+--------+

A.x min &lt; B.x min &lt; A.x max &lt; Bx max ⇒重叠X坐标: Bx min - Ax max


案例3 - 完全重叠:

+--------+
|A       |
| +----+ |
| |B   | |
| +----+ |
|        |
+--------+

A.x min &lt; B.x min &lt; B.x max &lt; Ax max ⇒重叠X坐标: Bx min - Bx max


P.S。:您实际上可以进一步简化此算法。重叠X坐标始终为:

  

max( Ax min Bx min ) - min( Ax max Bx max

除非第二个值小于第一个值;这意味着没有重叠。

答案 2 :(得分:4)

static internal Rectangle intersect(Rectangle lhs, Rectangle rhs)
{
    Dimension lhsLeft = lhs.Location.X;
    Dimension rhsLeft = rhs.Location.X;
    Dimension lhsTop = lhs.Location.Y;
    Dimension rhsTop = rhs.Location.Y;
    Dimension lhsRight = lhs.Right;
    Dimension rhsRight = rhs.Right;
    Dimension lhsBottom = lhs.Bottom;
    Dimension rhsBottom = rhs.Bottom;

    Dimension left = Dimension.max(lhsLeft, rhsLeft);
    Dimension top = Dimension.max(lhsTop, rhsTop);
    Dimension right = Dimension.min(lhsRight, rhsRight);
    Dimension bottom = Dimension.min(lhsBottom, rhsBottom);
    Point location = new Point(left, top);
    Dimension width = (right > left) ? (right - left) : new Dimension(0);
    Dimension height = (bottom > top) ? (bottom - top) : new Dimension(0);

    return new Rectangle(location, new Size(width, height));
}

答案 3 :(得分:1)

假设:

Points of   rectangle R1: R1.A(x,y), R1.B(x,y), R1.C(x,y), R1.D(x,y)   
Points of   rectangle R2: R2.A(x,y), R2.B(x,y), R2.C(x,y), R2.D(x,y)   
Overlapping rectangle RO: RO.A(x,y), RO.B(x,y), RO.C(x,y), RO.D(x,y)    
Standard cartesian coordinates (positive is right and upwards).

重叠矩形RO使用C#计算如下:

RO.A.x = Math.Min(R1.A.x, R2.A.x);
RO.A.y = Math.Max(R1.A.y, R2.A.y);
RO.C.x = Math.Max(R1.C.x, R2.C.x);
RO.C.y = Math.Min(R1.C.y, R2.C.y);
RO.B(x,y) and RO.D(x,y) = ....

内部矩形RI:

在上面的解决方案中交换最小和最大值以重叠矩形RO。

答案 4 :(得分:0)

我为我的项目使用了一个抽象验证器,并检查一些布局是否控制重叠我在布局图中创建了矩形:

RuleFor(p => DoControlsIntersect(p.PageControls.Select(x => new Rectangle(x.Row, x.Column, x.Width, x.Height)).ToList())).Equal(false).WithMessage(OverlappingFields);

private bool DoControlsIntersect(List<Rectangle> rectangles)
        {
            return rectangles.Any(rect => rectangles.Where(r => !r.Equals(rect)).Any(r => r.IntersectsWith(rect)));
        }