Skip to content

Instantly share code, notes, and snippets.

@surakamy
Created October 28, 2019 08:48
Show Gist options
  • Save surakamy/5503bbf3c4b9cb9305aa79bd40dd6d0b to your computer and use it in GitHub Desktop.
Save surakamy/5503bbf3c4b9cb9305aa79bd40dd6d0b to your computer and use it in GitHub Desktop.
SwiftUI animation demo
import SwiftUI
struct Vector: VectorArithmetic {
static func -= (lhs: inout Vector, rhs: Vector) {
lhs = lhs - rhs
}
static func - (lhs: Vector, rhs: Vector) -> Vector {
Vector(points: zip(lhs.points, rhs.points).map { $0.0 - $0.1 } )
}
static func += (lhs: inout Vector, rhs: Vector) {
lhs = lhs + rhs
}
static func + (lhs: Vector, rhs: Vector) -> Vector {
Vector(points: zip(lhs.points, rhs.points).map { $0.0 + $0.1 } )
}
mutating func scale(by rhs: Double) {
points = points.map { $0 * rhs }
}
var magnitudeSquared: Double {
self.points.reduce(1, { $0 + $1 * $1 })
}
static var zero: Vector { Vector(points: []) }
var points: [Double]
}
struct Elevation: Shape {
var data: Vector
var animatableData: Vector {
get { data }
set { data = newValue }
}
func path(in rect: CGRect) -> Path {
let path = Path { p in
let start = CGPoint(x: 0, y: 1)
p.move(to: start)
if !data.points.isEmpty {
for (i, l) in data.points.dropLast().enumerated() {
let pp = CGPoint(x: Double(i) * Double(1) / Double(data.points.count), y: l)
p.addLine(to: pp)
}
p.addLine(to: CGPoint(x: 1, y: data.points.last!))
}
p.addLine(to: CGPoint(x: 1, y: 1))
}
.applying(CGAffineTransform(scaleX: rect.width, y: rect.height))
return path
}
}
struct ContentView: View {
var timer = Timer.publish(every: 0.2, on: .main, in: .common).autoconnect()
@State var trail = Vector(points: (1...50).map( { _ in Double.random(in: 0.5...0.8)}))
func randomize() {
trail = Vector(points: (1...130).map( { _ in Double.random(in: 0.3...0.7)}))
}
var body: some View {
ZStack {
Color.black.edgesIgnoringSafeArea(.all)
Text("SwiftUI")
.foregroundColor(.white)
.font(.system(size: 70))
.offset(x: 0, y: 40)
.rotationEffect(Angle(degrees: 180))
Elevation(data: trail)
.foregroundColor(.blue)
.frame(width: 300, height: 1000)
.clipShape(
Circle()
)
.animation(.interpolatingSpring(stiffness: 50, damping: 10))
Elevation(data: trail)
.foregroundColor(.yellow)
.frame(width: 300, height: 800)
.clipShape(
Circle()
)
.animation(.interpolatingSpring(stiffness: 50, damping: 10))
Elevation(data: trail)
.foregroundColor(.orange)
.frame(width: 300, height: 600)
.clipShape(
Circle()
)
.animation(.interpolatingSpring(stiffness: 50, damping: 10))
Elevation(data: trail)
.foregroundColor(.red)
.frame(width: 300, height: 400)
.clipShape(
Circle()
)
.animation(.interpolatingSpring(stiffness: 50, damping: 10))
}.rotationEffect(Angle(degrees: -180))
.onReceive(timer) { _ in
self.randomize()
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment