美文网首页
iOS 向量运算

iOS 向量运算

作者: Trigger_o | 来源:发表于2021-04-22 15:51 被阅读0次

    整理了几个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
            }
        }
    
    }
    

    相关文章

      网友评论

          本文标题:iOS 向量运算

          本文链接:https://www.haomeiwen.com/subject/emqfrltx.html