点是否在多边形内

/// <summary>
        /// 点是否在多边形内
        /// </summary>
        /// <param name="boundary">构成边界的点</param>
        /// <param name="point">检查的点</param>
        /// <returns>是或否</returns>
        private bool InBoudary(List<PointD> boundary, PointD point,double xMax)
        {
            //作point点的一条水平线段
            PointD pointMax = new PointD(xMax, point.Y);

            bool isInBoundary = true;//是否在边界内
            int insectNum = 0;//相交的个数
            for (int i = 0; i < boundary.Count-1; i++)
            {
                //判断线段向上还是向下
                double yMax = 0, yMin = 0;
                if (boundary[i].Y>boundary[i+1].Y)
                {
                    yMax = boundary[i].Y;
                    yMin = boundary[i + 1].Y;
                }
                else
                {
                    yMin = boundary[i].Y;
                    yMax = boundary[i + 1].Y;
                }

                //判断线段是否相交
                //快速检验
                if (boundary[i].Y==boundary[i+1].Y||yMax<point.Y||yMin>point.Y)
                {
                    continue;
                }
                else
                {
                    double firstCross = (point.X - boundary[i].X) * (boundary[i + 1].Y - boundary[i].Y) - (point.Y - boundary[i].Y) * (boundary[i + 1].X - boundary[i].X);
                    double secondCross = (pointMax.X - boundary[i].X) * (boundary[i + 1].Y - boundary[i].Y) - (pointMax.Y - boundary[i].Y) * (boundary[i + 1].X - boundary[i].X);
                    double cross = firstCross * secondCross;
                    //>0 不相交
                    if (cross>0)
                    {
                        continue;
                    }
                    else
                    {
                        //向下
                        if (boundary[i].Y>boundary[i+1].Y)
                        {
                            if (point.Y==boundary[i].Y)
                            {
                                continue;
                            }
                            else
                            {
                                insectNum++;
                            }
                        }
                        else
                        {
                            if (point.Y == boundary[i+1].Y)
                            {
                                continue;
                            }
                            else
                            {
                                insectNum++;
                            }
                        }
                       
                    }
                }
            }

            //如果相交个数为奇数则在多边形内部
            if (insectNum%2==0)
            {
                isInBoundary = false;
            }
            return isInBoundary;
        }

猜你喜欢

转载自blog.csdn.net/Sun_xiangyan/article/details/82910948