如何判断一个点是否在多边形内部?
(1)面积和判别法:判断目标点与多边形的每条边组成的三角形面积和是否等于该多边形,相等则在多边形内部。
(2)夹角和判别法:判断目标点与所有边的夹角和是否为360度,为360度则在多边形内部。
(3)引射线法:从目标点出发引一条射线,看这条射线和多边形所有边的交点数目。如果有奇数个交点,则说明在内部,如果有偶数个交点,则说明在外部。
具体做法:将测试点的Y坐标与多边形的每一个点进行比较,会得到一个测试点所在的行与多边形边的交点的列表。在下图的这个例子中有8条边与测试点所在的行相交,而有6条边没有相交。如果测试点的两边点的个数都是奇数个则该测试点在多边形内,否则在多边形外。在这个例子中测试点的左边有5个交点,右边有三个交点,它们都是奇数,所以点在多边形内。
算法图解:
C++实现
/*Globals which should be set before calling this function:
int polySides = how many corners the polygon has
float polyX[] = horizontalcoordinates of corners
float polyY[] = verticalcoordinates of corners
float x,y = point to be tested
(Globals are used in this example for purposes of speed. Change as
desired.)
Thefunction will return YES if the point x,y is inside the polygon, or
NOif it is not. If the point is exactly on the edge of the polygon,
then the function may return YES or NO.
Note that division by zero is avoided because the division is protected
bythe "if" clause which surrounds it.*/
bool pointInPolygon(int polySizes,float x,float y,float polyX[],float polyY[])
{
int i,j=polySizes-1;
bool oddNodes = false;
for (i=0;i<polySizes; i++)
{
if((polyY[i]< y && polyY[j]>=y
|| polyY[j]<y && polyY[i]>=y)
&& (polyX[i]<=x || polyX[j]<=x))
{
oddNodes^=(polyX[i]+(y-polyY[i])/(polyY[j]-polyY[i])*(polyX[j]-polyX[i])<x);
/* if(polyX[i]+(y-polyY[i])/(polyY[j]-polyY[i])*(polyX[j]-polyX[i])<x)
{
oddNodes=!oddNodes;
}*/
}
j=i;
}
return oddNodes;
}
参考:
1、http://blog.csdn.net/hjh2005/article/details/9246967
2、http://www.cnblogs.com/luxiaoxun/p/3722358.html