简体   繁体   中英

How do i find the distance between two points/pixels?

I have this method:

private static List<Point> ExtendPoints(Point pt1, Point pt2)
{
    List<Point> ExtendedPoints = new List<Point>();
    decimal i = (Math.Sqrt(Math.Pow(Math.Abs(pt1.X - pt2.X), 2) + Math.Pow(Math.Abs(pt1.Y - pt2.Y), 2) + Math.Pow(Math.Abs(z1 - z2), 2)));

    return ExtendedPoints;
}

I need to find the exact x and y coordinate between the two points pt1 and pt2. The result should for example: 12,13 and this coordinate is exactly in the middle between the two points.

The way im doing it now with the decimal and the Math calculation is not the right way.

Just add the value of the components and divide by 2:

private static Point MidPoint(Point pt1, Point pt2)
{
    var midX = (pt1.X + pt2.X) / 2;
    var midY = (pt1.Y + pt2.Y) / 2;
    return new Point(midX, midY);
}

Mind you, not sure which Point class you're using. If it's System.Drawing.Point you may have issues with integer truncation.

Also, I'm not sure what you're trying to do with the List<Point> ExtendedPoints as, as far as I'm aware, there's only 1 midpoint between two points. I'm also not sure what you're doing with the z1 and z2 . If you're using 3 dimensional points, you can extend my answer and add the third dimension easily.

为什么不这样

double dist = Math.Sqrt(Math.Pow(x2 - x1, 2) + Math.Pow(y2 - y1, 2));

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