const QPoint &l2,
float &distance
) {
float lineMag;
float u;
lineMag = magnitude( l2, l1 );
u = ( ( ( p.x() - l1.x() ) * ( l2.x() - l1.x() ) ) +
( ( p.y() - l1.y() ) * ( l2.y() - l1.y() ) ) ) /
( lineMag * lineMag );
if ( u < 0.0f || u > 1.0f )
return false; // closest point does not fall within the line segment
intersectPnt.setX( int( l1.x() + u * ( l2.x() - l1.x() ) ) );
intersectPnt.setY( int( l1.y() + u * ( l2.y() - l1.y() ) ) );
distance = magnitude( p, intersectPnt );
return true;
}
{
float vx, vy;
vx = p2.x() - p1.x();
vy = p2.y() - p1.y();
return sqrt( vx * vx + vy * vy );
}
bool distancePointLine( const QPoint &p, const QPoint &l1,
const QPoint &l2, float &distance )
{
float lineMag;
float u;
QPoint intersectPnt;
lineMag = magnitude( l2, l1 );
u = ( ( ( p.x() - l1.x() ) * ( l2.x() - l1.x() ) ) +
( ( p.y() - l1.y() ) * ( l2.y() - l1.y() ) ) ) /
( lineMag * lineMag );
if ( u < 0.0f || u > 1.0f )
return false; // closest point does not fall within the line segment
intersectPnt.setX( int( l1.x() + u * ( l2.x() - l1.x() ) ) );
intersectPnt.setY( int( l1.y() + u * ( l2.y() - l1.y() ) ) );
distance = magnitude( p, intersectPnt );
return true;
}
float magnitude( const QPoint &p1, const QPoint &p2 )
{
float vx, vy;
vx = p2.x() - p1.x();
vy = p2.y() - p1.y();
return sqrt( vx * vx + vy * vy );
}
To copy to clipboard, switch view to plain text mode
This code is not the nicest, but it works.
Returns true of the point p is on the line segment defined by l1 and l2. The distance contains the distance between the point and the line.
Bookmarks