Two Rectangles intersection

后端 未结 7 2102
北海茫月
北海茫月 2020-11-27 16:39

I have two rectangles characterized by 4 values each :

Left position X, top position Y, width W and height H:

7条回答
  •  攒了一身酷
    2020-11-27 17:01

    If the rectangles' coordinates of the lower left corner and upper right corner are :
    (r1x1, r1y1), (r1x2, r1y2) for rect1 and
    (r2x1, r2y1), (r2x2, r2y2) for rect2
    (Python like code below)

        intersect = False
        for x in [r1x1, r1x2]:
            if (r2x1<=x<=r2x2):
                for y in [r1y1, r1y2]:
                    if (r2y1<=y<=r2y2):
                        intersect = True
                        return intersect
                    else:
                        for Y in [r2y1, r2y2]:
                            if (r1y1<=Y<=r1y2):
                                intersect = True
                                return intersect
            else:  
                for X in [r2x1, r2x2]:
                    if (r1x1<=X<=r1x2):
                        for y in [r2y1, r2y2]:
                            if (r1y1<=y<=r1y2):
                                intersect = True
                                return intersect
                            else:
                                for Y in [r1y1, r1y2]:
                                    if (r2y1<=Y<=r2y2):
                                        intersect = True
                                        return intersect
        return intersect
    

提交回复
热议问题