Area of rectangle-rectangle intersection

后端 未结 6 1016
夕颜
夕颜 2020-11-29 06:26

Below are 2 rectangles. Given the coordinates of the rectangle vertices - (x1, y1)...(x8, y8), how can the area of the overlapping region (white in the figure below

6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-29 07:11

    If you happen to use Qt then the intersection can be computed as QPolygonF intersection. Roughly as so:

    QPolygonF p1,p2, intersected;
    p1 << QPointF(r1x1,r1y1) << ... << QPointF(r1x4, r1y4);
    p2 << QPointF(r2x1,r2y2) << ... << QPointF(r2x4, r2y4);
    intersected = p1.intersected(p2);
    
    float area = polyArea(intersected); // see code block below
    

    (r1 = rectangle 1, r2 = rectangle 2, with 4 respective x and y coordinates).

    Now compute the area (using the already mentioned Shoelace formula):

    inline float polyArea(const QPolygonF& p)
    {
        //https://en.wikipedia.org/wiki/Polygon#Area_and_centroid
        const int n = p.size();
        float area = 0.0;
        for (int i=0; i

    My code here: public domain

提交回复
热议问题