计算两条线段是否相交 并返回相交的位置
0x01 调用方式
Point s1 = new Point ( 50 , 50 ) ;
Point e1 = new Point ( 50 , 250 ) ;
Point s2 = new Point ( - 20 , 85 ) ;
Point e2 = new Point ( 650 , 85 ) ;
var pp = GetIntersection ( s1, e1, s2, e2) ;
if ( pp. HasValue)
{
Console. WriteLine ( pp) ;
}
0x02 源码
private static Nullable< Point> GetIntersection ( Point a, Point b, Point c, Point d)
{
Point intersection = new Point ( 0 , 0 ) ;
if ( Math. Abs ( b. X - a. Y) + Math. Abs ( b. X - a. X) + Math. Abs ( d. Y - c. Y) + Math. Abs ( d. X - c. X) == 0 )
{
return null ;
}
if ( Math. Abs ( b. Y - a. Y) + Math. Abs ( b. X - a. X) == 0 )
{
return null ;
}
if ( ( b. Y - a. Y) * ( c. X - d. X) - ( b. X - a. X) * ( c. Y - d. Y) == 0 )
{
return null ;
}
intersection. X = ( ( b. X - a. X) * ( c. X - d. X) * ( c. Y - a. Y) - c. X * ( b. X - a. X) * ( c. Y - d. Y) + a. X * ( b. Y - a. Y) * ( c. X - d. X) ) / ( ( b. Y - a. Y) * ( c. X - d. X) - ( b. X - a. X) * ( c. Y - d. Y) ) ;
intersection. Y = ( ( b. Y - a. Y) * ( c. Y - d. Y) * ( c. X - a. X) - c. Y * ( b. Y - a. Y) * ( c. X - d. X) + a. Y * ( b. X - a. X) * ( c. Y - d. Y) ) / ( ( b. X - a. X) * ( c. Y - d. Y) - ( b. Y - a. Y) * ( c. X - d. X) ) ;
if ( ( intersection. X - a. X) * ( intersection. X - b. X) <= 0 && ( intersection. X - c. X) * ( intersection. X - d. X) <= 0 && ( intersection. Y - a. Y) * ( intersection. Y - b. Y) <= 0 && ( intersection. Y - c. Y) * ( intersection. Y - d. Y) <= 0 )
{
return intersection;
}
else
{
return null ;
}
}