如何判断一个点是否在多边形内?C++实现

    技术2023-06-22  81

    这里使用的是W. Randolph Franklin博士的方法。论文内容可参考https://www.cnblogs.com/reedlau/p/5731846.html。

    参数说明:

    其中Point2d为自定义结构体,也可定义为其他类型。

    struct Point2d { double x=0; double y=0; };

    P:需要判断的点。

    vector<Point2d>& polyVertices:多边形的顶点。

    bool isPointInsidePoly(const Point2d& P,const std::vector<Point2d>& polyVertices) { std::size_t vertCount = polyVertices.size(); if (vertCount < 2) return false; bool inside = false; for (unsigned i = 1; i <= vertCount; ++i) { const Point2d& A = polyVertices[i - 1]; const Point2d& B = polyVertices[i%vertCount]; if ((B.y <= P.y && P.y < A.y) || (A.y <= P.y && P.y < B.y)) { float t = (P.x - B.x)*(A.y - B.y) - (A.x - B.x)*(P.y - B.y); if (A.y < B.y) t = -t; if (t < 0) inside = !inside; } } return inside; }

     

    Processed: 0.014, SQL: 10