闲坐敲棋

有约不来过夜半,闲敲棋子落灯花

导航

C# 点在多边形内

Posted on 2009-06-20 17:17  闲坐敲棋  阅读(621)  评论(1编辑  收藏  举报
  • //这个算法是参考计算机图形学书上的算法得来的,可以说十分简单高效。   (C++)
  • //calc point in ploygon or not    
  • bool PIP(CPoint p,const CPoint data[],int n){   
  •     bool flag=0;   
  •     for(int i=0;i<n;i++){   
  •         if(p.y<data[i].y&&p.y<data[(i+1)%n].y)   
  •             continue;   
  •         if(data[i].x<=p.x&&data[(i+1)%n].x<=p.x)   
  •             continue;   
  •         int dx=data[(i+1)%n].x-data[i].x;   
  •         int dy=data[(i+1)%n].y-data[i].y;   
  •         float t=float(p.x-data[i].x)/dx;//求得交点的t值   
  •          float y=t*dy+data[i].y;   
  •         if(y<=p.y&&t>=0&&t<=1)   
  •         flag=!flag;   
  •     }   
  •     return flag;   
  • }  
  •  

    ----------------------------------------------------------------

    c# 测试代码

     

     

    namespace _062001
    {
        class Program
        {
            static void Main(string[] args)
            {
                Point[] data = new Point[4];
                data[0] = new Point(0, 0);
                data[1] = new Point(0, 5);
                data[2] = new Point(5, 5);
                data[3] = new Point(5, 0);

                Point p = new Point(3, 3);
                if (PIP(p,data,4))
                {
                    Console.WriteLine("在区域内");
                }else{
                    Console.WriteLine("不在区域内");
                }
            }

            static bool PIP(Point p,Point[] data,int n)
            {
                bool flag =false;
                for (int i=0;i<n;i++)
                {
                    if (p.Y <data[i].Y && p.Y<data[(i+1)%n].Y)
                          continue;
                    if (data[i].X <p.X && data[(i+1)%n].X <p.X)
                          continue;
                    float dx = data[(i+1)%n].X - data[i].X;
                    float dy = data[(i+1)%n].Y - data[i].Y;
                    float t= (float)((p.X - data[i].X)/dx);
                    float y = t*dx + data[i].Y;
                    if (y<p.Y && t>=0 && t<=1)
                          flag =!flag;
                }
                return flag;
            }
        }
        class Point
        {
            private float x;

            public float X
            {
                get { return x; }
                set { x = value; }
            }
            private float y;
            public float Y
            {
                get { return y; }
                set { y = value; }
            }

            public Point(float p_x,float p_y)
            {
                x = p_x;
                y = p_y;
            }

        }
       
    }