简体   繁体   中英

Get the distance from a Point to a Geometry

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

在此处输入图片说明

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...

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.

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