iOS 向量运算

2021-04-22  本文已影响0人  Trigger_o

整理了几个swift向量运算的方法

extension CGVector {
    
    ///加法
    static func +(v1: CGVector, v2: CGVector) -> CGVector {
        return CGVector(dx: v1.dx + v2.dx, dy: v1.dy + v2.dy)
    }
    
    static func +=(v1: inout CGVector, v2: CGVector) {
        v1 = v1 + v2
    }
        
    ///减法
    static func -(v1: CGVector, v2: CGVector) -> CGVector {
        return CGVector(dx: v1.dx - v2.dx, dy: v1.dy - v2.dy)
    }
    
    static func -= (v1: inout CGVector, v2: CGVector) {
        v1 = v1 - v2
    }
    
    ///乘法
    static func *(vector: CGVector, scalar: CGFloat) -> CGVector {
        return CGVector(dx: vector.dx * scalar, dy: vector.dy * scalar)
    }
    
    static func *(scalar: CGFloat, vector: CGVector) -> CGVector {
        return CGVector(dx: vector.dx * scalar, dy: vector.dy * scalar)
    }
    
    static func *= (vector: inout CGVector, scalar: CGFloat) {
        vector = vector * scalar
    }
    
    //除法
    static func /(v1: CGVector, scalar: CGFloat) -> CGVector {
        return CGVector(dx: v1.dx / scalar, dy: v1.dy / scalar)
    }
    
    static func /= (vector: inout CGVector, scalar: CGFloat) {
        vector = vector / scalar
    }
    
    /// 向量的大小
    var length: CGFloat {
        get {
            return sqrt(dx * dx + dy * dy)
        }
    }
    
    /// 单位向量
    var normalizer: CGVector {
        get {
            return self / length
        }
    }

}
上一篇下一篇

猜你喜欢

热点阅读