CGVector Extension
2018-12-13 10:44 法子 阅读(612) 评论(0) 编辑 收藏 举报向量的大小、求和、正规化等
extension CGVector { /// 向量的大小 var length: Double { get { let dx = Double(self.dx) let dy = Double(self.dy) return sqrt(dx * dx + dy * dy) } } /// Normalizing var normalizer: CGVector { get { return self / length } } var angle: Double { get { return atan2(Double(dy), Double(dx)) } } /// 向量加法 /// /// - Parameters: /// - left: One Vector /// - right: Other Vector /// - Returns: 向量的和 static func +(left: CGVector, right: CGVector) -> CGVector { return CGVector(dx: left.dx + right.dx, dy: left.dy + right.dy) } static func +=(left: inout CGVector, right: CGVector) { left = left + right } static func *(vector: CGVector, scalar: Double) -> CGVector { return CGVector(dx: Double(vector.dx) * scalar, dy: Double(vector.dy) * scalar) } static func *(scalar: Double, vector: CGVector) -> CGVector { return CGVector(dx: Double(vector.dx) * scalar, dy: Double(vector.dy) * scalar) } static func *= (vector: inout CGVector, scalar: Double) { vector = vector * scalar } static func -(left: CGVector, right: CGVector) -> CGVector { return CGVector(dx: left.dx - right.dx, dy: left.dy - right.dy) } static func -= (left: inout CGVector, right: CGVector) { left = left - right } static func /(left: CGVector, scalar: Double) -> CGVector { return CGVector(dx: Double(left.dx) / scalar, dy: Double(left.dy) / scalar) } static func /= (vector: inout CGVector, scalar: Double) { vector = vector / scalar } } /* //如果不写在最外层而是写在类里面,要写成static func +(left: CGVector, right: CGVector) -> CGVector { return CGVector(dx: left.dx + right.dx, dy: left.dy + right.dy) } */