//判断点是否在四边形内,该函数也适用于多边形,将点数改成你想要的边数就行
bool MyPtInRect(Point2d pCur, Point2d pLeftTop, Point2d pRightTop, Point2d pRightBelow, Point2d pLeftBelow)
{
int nCount = 4;//任意四边形有4个顶点
Point2d RectPoints[4] = { pLeftTop, pLeftBelow, pRightBelow, pRightTop };
int nCross = 0;
double lastPointX = -999.999;
for (int i = 0; i < nCount; i++)
{
//依次取相邻的两个点
Point2d pBegin = RectPoints[i];
Point2d pEnd = RectPoints[(i + 1) % nCount];
//相邻的两个点是平行于x轴的,当前点和x轴的平行线要么重合,要么不相交,不算
if (pBegin.y == pEnd.y)continue;
//交点在pBegin,pEnd的延长线上,不算
if (pCur.y < min(pBegin.y, pEnd.y) || pCur.y > max(pBegin.y, pEnd.y))continue;
//当前点和x轴的平行线与pBegin,pEnd直线的交点的x坐标
double x = (double)(pCur.y - pBegin.y) * (double)(pEnd.x - pBegin.x) / (double)(pEnd.y - pBegin.y) + pBegin.x;
if (x > pCur.x)//只看pCur右边交点
{
if (x != lastPointX)//防止角点算两次
{
nCross++;
lastPointX = x;
}
}
}
// 单方向交点为奇数,点在多边形之内
// 单方向交点为偶数,点在多边形之外
return (nCross % 2 == 1);
}
11-13
5368