点在多边形内部(不包括多边形上)
// Globals which should be set before calling this function:
//
// int polySides = how many cornersthe 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 i,j=polySides-1 ;
bool oddNodes=NO ;
for (i=0;i<polySides; 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);}
j=i;}
returnoddNodes; }
点在线段上判别法
//
// 平面点的距离公式
#define DISTANCE2(x1,y1,x2,y2) ((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2))
//
// {{判断点是否在线段上
double cval = DISTANCE2(x,y,pt2di.x,pt2di.y) + DISTANCE2(x,y,pt2dj.x,pt2dj.y)
- DISTANCE2(pt2di.x,pt2di.y,pt2dj.x,pt2dj.y);
if(cval < 0.000001)
{
// 排除端点
if((abs(x - pt2di.x) < 0.0000001 && abs(y - pt2di.y) < 0.0000001) ||
(abs(x - pt2dj.x) < 0.0000001 && abs(y - pt2dj.y) < 0.0000001) )
{
return 1;
}
if(x - min(pt2di.x,pt2dj.x) >= 0.0 && max(pt2di.x,pt2dj.x) - x >= 0.0)
{
if(y - min(pt2di.y,pt2dj.y) >= 0.0 && max(pt2di.y,pt2dj.y) - y >= 0.0)
return 1;
}
}
// }}