多边形是否包含点的算法

public static bool PolygonContains(MyPolygon polygon, MyPoint point)
        {
            if (polygon == null)
            {
                return false;
            }
            //删除最后一个顶点
            int polygonVerticesCount = polygon.Length;
            var polygonVertices = polygon.Points;
            if (polygonVertices[0].Equals(polygonVertices[polygonVertices.Count - 1]))
            {
                polygonVerticesCount -= 1;
            }

            double A, B, C, D;
            int count = 0;
            for (int i = 0; i < polygonVerticesCount; i++)
            {//[0,1]..[n-2,n-1]
                var p1 = polygonVertices[i] as MyPoint;
                var p2 = polygonVertices[(i + 1) % polygonVertices.Count] as MyPoint;
                bool t1 = p1.X > p2.X;
                bool t2 = p1.X > point.X;
                bool t3 = p2.X > point.X;
                if (t2 != t3)
                {
                    A = p2.Y - p1.Y;
                    B = p1.X - p2.X;
                    C = -A * p1.X - B * p1.Y;
                    D = A * point.X + B * point.Y + C;
                    if (D < 0 && t1)
                    {
                        count++;
                    }
                    if (D > 0 && t1 == false)
                    {
                        count++;
                    }
                }
                else if ((t2 == false) && (t3 == false))
                {
                    if (t1 && p2.X == point.X)
                    {
                        count++;
                    }
                    if ((t1 == false) && p1.X == point.X)
                    {
                        count++;
                    }

                }
            }

            if (count % 2 == 1)
            {
                return true;
            }
            return false;
        }

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值