简体   繁体   中英

How to find neighbor Points on Line/Polyline c#

I have a problem with finding neighbor points on a line.

I have a polyline and a point. The point always stay on the line. Lines are always straight (not oblique).

I would like to find previous and following points. (on the image these are C and D). What is the best way to do this? It may be better to find previous point (then, finding the next point will be trivial).

My idea was use loops and if statements, but maybe there exists a better solution?

在此处输入图片说明

Here is a naive solution if you can fit your grid into int values. It should cover the cases when the line is not "growing" like squared spiral. When switching to double, be aware of possible rounding problems.

            var line = new List<Point>
        {
            new Point("A", 0, 0),
            new Point("B", 1, 0),
            new Point("C", 1, 1),
            new Point("D", 3, 1),
            new Point("E", 3, 2),
            new Point("F", 4, 2)
        };

        var p = new Point("P",2,1);

        Point first = null;
        foreach (var point in line)
        {
            if (first != null)
            {
                if (p.X == first.X && p.X == point.X
                    && (p.Y >= first.Y && p.Y <= point.Y
                        || p.Y <= first.Y && p.Y >= point.Y))
                {
                    PrintResult(first, p, point);
                    break;
                }

                if (p.Y == first.Y && p.Y == point.Y
                    && (p.X >= first.X && p.X <= point.X
                        || p.X <= first.X && p.X >= point.X))
                {
                    PrintResult(first, p, point);
                    break;
                }

            }

            first = point;
        }

        Console.ReadKey();
    }

    private static void PrintResult(Point first, Point p, Point second)
    {
        Console.WriteLine(first.Name);
        Console.WriteLine(p.Name);
        Console.WriteLine(second.Name);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM