/// 计算3个点之间的角度
///
/// - Parameters:
/// - p1: 一端
/// - p2: 另一端
/// - p0: 中间点
/// - Returns: 角度 单位:°(度)
public func computeAngle(_ p1: CGPoint,_ p2: CGPoint,_ p0: CGPoint) -> CGFloat{
let dx1 = p1.x - p0.x;
let dy1 = p1.y - p0.y;
let dx2 = p2.x - p0.x;
let dy2 = p2.y - p0.y;
let cos_angle = (dx1*dx2 + dy1*dy2)/sqrt((dx1*dx1 + dy1*dy1)*(dx2*dx2 + dy2*dy2) + 1e-10)
return acos(cos_angle) * 180.0 / CGFloat.pi
}
/// 一般式 直线方程 Ax + By + C = 0
public typealias LinearEquation = (CGFloat,CGFloat,CGFloat)
/// 计算直线方程 一般式 Ax + By + C = 0
///
/// - Parameters:
/// - p1: 第一个点
/// - p2: 第二个点
/// - Returns: 一般式方程
public func computeLinearEquation(_ p1: CGPoint,_ p2: CGPoint) -> LinearEquation {
return (p2.y-p1.y,p1.x-p2.x,p1.y*p2.x-p1.x*p2.y)
}
/// 两线的交点
///
/// - Parameters:
/// - line1: 第一条一般式直线方程
/// - line2: 第二条一般式直线方程
/// - Returns: 交点
public func compute2lineIntersection(_ line1: LinearEquation, _ line2: LinearEquation) -> CGPoint?{
//斜率不存在
if line1.1 == 0 && line2.1 == 0 {
return nil
}
//斜率相等
if line1.0 / line1.1 == line2.0 / line2.1 {
return nil
}
//有交点
let x = (line1.1*line2.2 - line2.1*line1.2)/(line1.0*line2.1 - line2.0*line1.1)
let y = (line2.2*line1.0 - line1.2*line2.0)/(line2.0*line1.1 - line1.0*line2.1)
return CGPoint(x: x, y: y)
}
网友评论