How to get overlapping rectangle coordinates

后端 未结 5 1349

Assume I have the following overlapping rectangles (\"a\" and \"b\"):

aaaaaaaa
aaaaccccbbbbb
aaaaccccbbbbb
aaaaccccbbbbb
    bbbbbbbbb
    bbbbbbbbb
5条回答
  •  长发绾君心
    2021-02-09 05:03

    The X coordinates of the overlap area of two rectangles can be found according to the following logic.

    To find the Y coordinates, substitute Y for X in the last of the four assumptions, as well as in all of the three cases.


    Assumptions:

    • A and B are rectangles (with their sides aligned along the X and Y axes),

    • each of the rectangles is defined by two points   (xmin / ymin) – (xmax / ymax)

    • where xmin < xmax   and   ymin < ymax  .

    • A.xmin < B.xmin


    Case 1 — No overlap:

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

    A.xmin < A.xmax < B.xmin < B.xmax   ⇒   No overlap.


    Case 2 — Some overlap:

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

    A.xmin < B.xmin < A.xmax < B.xmax   ⇒   Overlap X coordinates: B.xminA.xmax


    Case 3 — Complete overlap:

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

    A.xmin < B.xmin < B.xmax < A.xmax   ⇒   Overlap X coordinates: B.xminB.xmax


    P.S.: You can actually further simplify this algorithm. The overlap X coordinates are always:

    max(A.xmin, B.xmin) – min(A.xmax, B.xmax)

    except when the second value is less than the first; that means that there is no overlap.

提交回复
热议问题