Question

I have System.Windows.Media.Geometry g and System.Windows.Point p.

enter image description here

I want to know the shortest distance between the point and the outline of the geometry. How should I do it?

Here is my effort:

  1. Geometry.GetOutlinedPathGeometry() returns PathGeometry.

  2. PathGeometry.Figures returns PathFigure.

  3. PathFigure.Segments returns PathSegment.

  4. No useful method on PathSegment...

Was it helpful?

Solution

Basically, what you need to do is go through every point on that path that you got from your geometry and measure distance between one of those points and the segregated point.

There's a post on SO that finds the closest point to the segregated point:

https://stackoverflow.com/a/19031758/2006048

And there's a C++ algorithm that does the distance measuring. You'll just have to convert it to C#:

https://stackoverflow.com/a/1501725/2006048

You can probably also use Point.Subtract() method to get and compare Vectors between each of those points.

If you can get an array or list of points from that shape, then you can probably do something like this (Note that this is not as elaborate as the links I've provided. This will give you the shortest distance to one of the available points and not the segment itself):

public static double GetShortestDistance(Point target, Point[] points)
{
    var dist = 0;
    foreach (var point in points)
    {
        var xDist = target.X - point.X;
        var yDist = target.Y - point.Y;
        var nDist = Math.Sqrt(xDist * xDist + yDist * yDist);

        if (nDist < dist)
        {
            dist = nDist;
        }
    }

    return dist;
}

I recommend using the C++ algorithm in the second link.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top