计算线上距离另一个点的最近点

时间:2014-06-12 13:53:42

标签: c# wpf algorithm

我试图在WPF中的路径上添加一个Point。在Xaml中一切正常。我有一条路径,当我点击它(或靠近它)时,我的Create Point Handler会被触发。它会为我创造一个Point,但是这个Point不会完全坐在我的路上。

我试着做一些计算来获得我的Point的精确坐标,但它变得更糟,现在我的点数与以前一样接近或者有时距离我的路径变得更大。我无法弄清楚为什么。继承我的事件处理程序,请帮助我。 (关于deviation的第一个计算是让我弄清楚我的List中的哪个索引我必须插入新的Point。这样工作正常。)

private void CreatePointHandler(MouseEventArgs e)
    {
        Path clickedPath = e.OriginalSource as Path;
        FrameworkElement parentCanvas = clickedPath.Parent as FrameworkElement;
        Point pos = e.GetPosition(parentCanvas);
        ConnectionPoint p = new ConnectionPoint(RaisePointsChanged);            

        for (int i = 0; i < Points.Count - 1; i++) {
            double d1 = (Math.Abs(Points[i].X - Points[i + 1].X)) * (Math.Abs(pos.Y - Points[i + 1].Y));
            double d2 = (Math.Abs(Points[i].Y - Points[i + 1].Y)) * (Math.Abs(pos.X - Points[i + 1].X));
            double deviation = Math.Abs(d1 - d2);
            if (deviation < 3000 && ((Points[i].X < pos.X && pos.X < Points[i+1].X) || (Points[i].X > pos.X && pos.X > Points[i+1].X))
                                 && ((Points[i].Y < pos.Y && pos.Y < Points[i+1].Y) || (Points[i].Y > pos.Y && pos.Y > Points[i+1].Y))) {

                Vector iToIPlus1 = new Vector(Points[i + 1].X - Points[i].X, Points[i + 1].Y - Points[i].Y);
                Vector iToPos = new Vector(pos.X - Points[i].X, pos.Y - Points[i].Y);


                double t = (iToPos.X * iToIPlus1.X + iToPos.Y * iToIPlus1.Y) / (iToIPlus1.X * iToIPlus1.X + iToIPlus1 * iToIPlus1);

                p.X = Points[i].X + t * iToIPlus1.X;
                p.Y = Points[i].Y + t * iToIPlus1.Y;

                Points.Insert(i + 1, p);
                return;
            }
        }                       
    }

0 个答案:

没有答案
相关问题