欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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

程序员文章站 2022-04-02 21:20:58
...

这里使用的是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;
}

 

相关标签: C++ c++ 多边形