首页 > 代码库 > 判断两条直线是否相交点

判断两条直线是否相交点

#pragma mark ------------ 判断两条直线是否相交
 
+ (BOOL)checkLineIntersection:(CGPoint)p1 p2:(CGPoint)p2 p3:(CGPoint)p3 p4:(CGPoint)p4
{
    CGFloat denominator = (p4.y - p3.y) * (p2.x - p1.x) - (p4.x - p3.x) * (p2.y - p1.y);
     
    if (denominator == 0.0f) {
         
        return NO;
    }
     
    CGFloat ua = ((p4.x - p3.x) * (p1.y - p3.y) - (p4.y - p3.y) * (p1.x - p3.x))/denominator;
    CGFloat ub = ((p2.x - p1.x) * (p1.y - p3.y) - (p2.y - p1.y) * (p1.x - p3.x))/denominator;
     
    if (ua >= 0.0f && ua <= 1.0f && ub >= 0.0f && ub <= 1.0f) {
         
        return YES;
    }
     
    return NO;
}
 
#pragma mark ------------ 两条直线要是相交 求出相交点
 
+ (CGPoint)intersectionU1:(CGPoint)u1 u2:(CGPoint)u2 v1:(CGPoint)v1 v2:(CGPoint)v2
{
    CGPoint ret = u1;
     
    double t = ((u1.x - v1.x) * (v1.y - v2.y) - (u1.y - v1.y) * (v1.x - v2.x))/((u1.x-u2.x) * (v1.y - v2.y) - (u1.y - u2.y) * (v1.x - v2.x));
     
    ret.x += (u2.x - u1.x) * t;
    ret.y += (u2.y - u1.y) * t;
     
    return ret;
}

判断两条直线是否相交点