c# 判断点与圆、矩形、多边形的关系

c#中并未提供类型GIS的空间结构,把点、圆、矩形、多边形等封装在一起,但是基本的空间位置关系还是可以判断的:

       //判断点与矩形、圆及多边形的位置关系
    public class PointHelper
    {
        public static Boolean PointInRect(Point p,Rectangle rect)
        {
            return rect.Contains(p);
        }
        public static Boolean PointInCircle(Point p, Point circleStart, Point circleEnd)
        {
            try
            {
                double radius = Math.Sqrt(Math.Pow(Math.Abs(circleStart.X - circleEnd.X), 2) + Math.Pow(Math.Abs(circleStart.Y - circleEnd.Y), 2));
                double distance = Math.Sqrt(Math.Pow(Math.Abs(circleStart.X - p.X), 2) + Math.Pow(Math.Abs(circleStart.Y - p.Y), 2));
                return distance <= radius;
            }
            catch (Exception ex)
            {
               
                return false;
            }
        }
        //str的格式:121.436372,31.3397;121.463393,31.3397;121.463393,31.327979;121.436372,31.32797
        public static Boolean PointInPolygon(Point p, String str)
        {
            try
            {
                List<Point> pList = getPointList(str);
                System.Drawing.Drawing2D.GraphicsPath myGraphicsPath = new System.Drawing.Drawing2D.GraphicsPath();
                Region myRegion = new Region();

                myGraphicsPath.Reset();
                myGraphicsPath.AddPolygon(pList.ToArray());
                myRegion.MakeEmpty();
                myRegion.Union(myGraphicsPath);
                //返回判断点是否在多边形里
                return myRegion.IsVisible(p);
            }
            catch (Exception ex)
            {
               
                return false;
            }
        }
        public static Point getPoint(string s)
        {
            try
            {
                Point p = new Point();
                string[] pArr = s.Split(',');
                p.X = (int)(double.Parse(pArr[0]) * 1000000);
                p.Y = (int)(double.Parse(pArr[1]) * 1000000);
                return p;
            }
            catch (Exception ex)
            {
                
                return new Point(); ;
            }
        }
        public static List<Point> getPointList(string str)
        {
            try
            {
                List<Point> pList = new List<Point>();
                if (str.Contains(";"))
                {
                    string[] pointArr = str.Split(';');
                    foreach (string s in pointArr)
                    {
                        if (s.Contains(","))
                        {
                            Point point = getPoint(s);
                            pList.Add(point);
                        }
                    }
                }
                return pList;
            }
            catch (Exception ex)
            {
               
                return null;
            }
        }
    }

 

 

posted @ 2013-07-01 16:13  nygfcn  阅读(954)  评论(0编辑  收藏  举报