0

I'm trying to put a Point on a Path in WPF. In the Xaml everything is working fine. I have a path and when i click on it (or near it) my Create Point Handler gets fired. It will create a Point for me, but this Point wont sit exactly on my path.

I tried to do some calculations to get the exact coordinates for my Point, but it got even worse, now my points are as close as before or sometimes the distance to my path gets even bigger. I cannot figure out why. Heres my event handler, please help me. (The first calculation regarding deviation is for me to figure out at which index in my List i have to insert the new Point. This is working fine.)

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;
            }
        }                       
    }
user3596113
  • 868
  • 14
  • 32
  • Is this what you are trying to do? http://forum.lessthandot.com/viewtopic.php?f=102&t=4675&start=0 – George Mastros Jun 12 '14 at 13:58
  • Sorry not quite. I'm not really interested in the distance in the first place. I just want to put my Point exactly on my Path. I cannot just use `pos.X`or `pos.Y` because, the event gets thrown even if the user clicks slightly beneath my path. I hope you understand. – user3596113 Jun 12 '14 at 14:01

0 Answers0