Proejct

두 점을 연결하는 선상의 포인트중 가장 가까운 포인트를 구하는 함수

백운성 2011. 9. 2. 11:23
// pts 는 선의 시작과 끝 포인트
// p   는 내가 선택한 포인트
// pb  는 p에 가장 근접한 pts선상의 포인트

static public double GetDistLinetoPoint(Point[] pts, Point p, out PointF Pb)

    {

 

      PointF v = new PointF(pts[1].X - pts[0].X, pts[1].Y - pts[0].Y);

      PointF w = new PointF(p.X - pts[0].X, p.Y - pts[0].Y);

 

      double c1 = Dot(w, v);

      if (c1 <= 0)

      {

        Pb = pts[0];

        return d(p, pts[0]);

      }

 

      double c2 = Dot(v, v);

      if (c2 <= c1)

      {

        Pb = pts[1];

        return d(p, pts[1]);

      }

 

      double b = c1 / c2;

      //PointF Pb = new PointF((float)(pts[0].X + v.X * b), (float)(pts[0].Y + v.Y * b));

      Pb = new PointF((float)(pts[0].X + v.X * b), (float)(pts[0].Y + v.Y * b));

 

      return d(p, Pb);

    }

static private double Dot(PointF p1, PointF p2)
    {
      return p1.X * p2.X + p1.Y * p2.Y;
    }

    static private double Norm(PointF p)
    {
      return Math.Sqrt(Dot(p, p));
    }

    static private double d(PointF p1, PointF p2)
    {
      PointF p = new PointF(p1.X - p2.X, p1.Y - p2.Y);
      return Norm(p);
    }