How can I tell if a point belongs to a certain line?

前端 未结 11 2196
你的背包
你的背包 2020-12-01 08:22

How can I tell if a point belongs to a certain line?

Examples are appreciated, if possible.

11条回答
  •  眼角桃花
    2020-12-01 08:43

    If you have a line defined by its endpoints

    PointF pt1, pt2;
    

    and you have a point that you want to check

    PointF checkPoint;
    

    then you could define a function as follows:

    bool IsOnLine(PointF endPoint1, PointF endPoint2, PointF checkPoint) 
    {
        return (checkPoint.Y - endPoint1.Y) / (endPoint2.Y - endPoint1.Y)
            == (checkPoint.X - endPoint1.X) / (endPoint2.X - endPoint1.X);
    }
    

    and call it as follows:

    if (IsOnLine(pt1, pt2, checkPoint) {
        // Is on line
    }
    

    You will need to check for division by zero though.

提交回复
热议问题