当前位置:   article > 正文

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

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

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

参数说明:

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

  1. struct Point2d
  2. {
  3. double x=0;
  4. double y=0;
  5. };

P:需要判断的点。

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

  1. /*顶点需按照顺时针或者逆时针排序,不能乱序*/
  2. bool isPointInsidePoly(const Point2d& P,const std::vector<Point2d>& polyVertices)
  3. {
  4. std::size_t vertCount = polyVertices.size();
  5. if (vertCount < 2)
  6. return false;
  7. bool inside = false;
  8. for (unsigned i = 1; i <= vertCount; ++i)
  9. {
  10. const Point2d& A = polyVertices[i - 1];
  11. const Point2d& B = polyVertices[i%vertCount];
  12. if ((B.y <= P.y && P.y < A.y) || (A.y <= P.y && P.y < B.y))
  13. {
  14. float t = (P.x - B.x)*(A.y - B.y) - (A.x - B.x)*(P.y - B.y);
  15. if (A.y < B.y)
  16. t = -t;
  17. if (t < 0)
  18. inside = !inside;
  19. }
  20. }
  21. return inside;
  22. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/木道寻08/article/detail/833757
推荐阅读
相关标签
  

闽ICP备14008679号