Skip to content

Instantly share code, notes, and snippets.

@mecid
Created June 17, 2020 23:40
Show Gist options
  • Save mecid/04ab91f45fec501e72e4d5fb02277f3f to your computer and use it in GitHub Desktop.
Save mecid/04ab91f45fec501e72e4d5fb02277f3f to your computer and use it in GitHub Desktop.
The type that holds array of CGPoints and conforms to VectorArithmetic
import SwiftUI
struct AnimatableCGPointVector: VectorArithmetic {
static var zero = AnimatableCGPointVector(values: [.zero])
static func - (lhs: AnimatableCGPointVector, rhs: AnimatableCGPointVector) -> AnimatableCGPointVector {
let values = zip(lhs.values, rhs.values)
.map { lhs, rhs in lhs.animatableData - rhs.animatableData }
.map { CGPoint(x: $0.first, y: $0.second) }
return AnimatableCGPointVector(values: values)
}
static func -= (lhs: inout AnimatableCGPointVector, rhs: AnimatableCGPointVector) {
for i in 0..<min(lhs.values.count, rhs.values.count) {
lhs.values[i].animatableData -= rhs.values[i].animatableData
}
}
static func + (lhs: AnimatableCGPointVector, rhs: AnimatableCGPointVector) -> AnimatableCGPointVector {
let values = zip(lhs.values, rhs.values)
.map { lhs, rhs in lhs.animatableData + rhs.animatableData }
.map { CGPoint(x: $0.first, y: $0.second) }
return AnimatableCGPointVector(values: values)
}
static func += (lhs: inout AnimatableCGPointVector, rhs: AnimatableCGPointVector) {
for i in 0..<min(lhs.values.count, rhs.values.count) {
lhs.values[i].animatableData += rhs.values[i].animatableData
}
}
var values: [CGPoint]
mutating func scale(by rhs: Double) {
for i in 0..<values.count {
values[i].animatableData.scale(by: rhs)
}
}
var magnitudeSquared: Double {
values
.map { $0.animatableData.magnitudeSquared }
.reduce(0.0, +)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment