簡體   English   中英

如何獲得重疊的矩形坐標

[英]How to get overlapping rectangle coordinates

假設我有以下重疊的矩形(“ a”和“ b”):

aaaaaaaa
aaaaccccbbbbb
aaaaccccbbbbb
aaaaccccbbbbb
    bbbbbbbbb
    bbbbbbbbb

我已經看到了許多有關如何計算內部矩形(“ c”)的面積的想法,但是我將如何獲取實際的頂部/左側/底部/右側坐標?

可以根據以下邏輯找到兩個矩形的重疊區域的X坐標。

要找到Y坐標,請在四個假設的最后一個以及所有三種情況下用Y替換X。


假設:

  • AB是矩形(其邊沿X和Y軸對齊),

  • 每個矩形都由兩個點( x min / y min )–( x max / y max )定義

  • 其中x min < x maxy min < y max

  • Ax 分鍾 < Bx 分鍾


情況1-無重疊:

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

Ax 最小值 < Ax 最大值 < Bx 最小值 < Bx 最大值 ⇒沒有重疊。


情況2-一些重疊:

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

分鍾 <Bx的 < MAX <Bx的最大值 ⇒重疊X坐標:Bx的最小 - 最大


情況3-完全重疊:

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

Ax 最小值 < Bx 最小值 < Bx 最大值 < Ax 最大值 ⇒重疊X坐標: Bx 最小值Bx 最大值


PS:您實際上可以進一步簡化此算法。 重疊的X坐標始終為:

max( Ax minBx min )– min( Ax maxBx max

除非第二個值小於第一個; 這意味着沒有重疊。

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

假設:

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:

在上面的解決方案中將Min和Max交換為重疊的矩形RO。

我為我的項目使用了一個抽象驗證器,並檢查是否有一些布局控件在重疊的地方從布局圖中創建了矩形:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM