Skip to content

Instantly share code, notes, and snippets.

@j0sm3n
Forked from davidsteppenbeck/KeyframeView.swift
Created May 7, 2024 09:30
Show Gist options
  • Save j0sm3n/d5d218f8d7d69a8d6609f6e1767eef41 to your computer and use it in GitHub Desktop.
Save j0sm3n/d5d218f8d7d69a8d6609f6e1767eef41 to your computer and use it in GitHub Desktop.
Keyframe Animation Example in SwiftUI
import SwiftUI
struct KeyframeValues {
var scale = 1.0
var horizontalStretch = 1.0
var verticalStretch = 1.0
var translation = 0.0
var rotation = Angle.zero
}
struct KeyframeView: View {
@State private var trigger: Bool = false
var body: some View {
ZStack {
Color.yellow
.ignoresSafeArea()
.onTapGesture {
trigger.toggle()
}
ImageView()
.keyframeAnimator(initialValue: KeyframeValues(), trigger: trigger) { content, value in
content
.scaleEffect(value.scale)
.scaleEffect(x: value.horizontalStretch, y: value.verticalStretch)
.offset(y: value.translation)
.rotationEffect(value.rotation)
} keyframes: { value in
KeyframeTrack(\.scale) {
LinearKeyframe(1.0, duration: 0.5)
SpringKeyframe(1.4, duration: 0.7)
SpringKeyframe(1.0, spring: .bouncy)
}
KeyframeTrack(\.translation) {
LinearKeyframe(0.0, duration: 0.4)
SpringKeyframe(15.0, duration: 0.1, spring: .bouncy)
SpringKeyframe(-50.0, duration: 0.7, spring: .bouncy)
SpringKeyframe(15.0, duration: 0.05, spring: .bouncy)
SpringKeyframe(0.0, spring: .bouncy)
}
KeyframeTrack(\.horizontalStretch) {
CubicKeyframe(1.0, duration: 0.4)
CubicKeyframe(1.6, duration: 0.1)
CubicKeyframe(0.8, duration: 0.05)
CubicKeyframe(0.95, duration: 0.15)
CubicKeyframe(1.0, duration: 0.7)
CubicKeyframe(1.1, duration: 0.15)
CubicKeyframe(1.0, duration: 0.2)
}
KeyframeTrack(\.verticalStretch) {
CubicKeyframe(1.0, duration: 0.4)
CubicKeyframe(0.8, duration: 0.1)
CubicKeyframe(1.2, duration: 0.05)
CubicKeyframe(1.05, duration: 0.15)
CubicKeyframe(1.0, duration: 0.7)
CubicKeyframe(0.9, duration: 0.15)
CubicKeyframe(1.0, duration: 0.2)
}
KeyframeTrack(\.rotation) {
LinearKeyframe(Angle.zero, duration: 0.8)
SpringKeyframe(Angle(degrees: 50), duration: 0.08)
SpringKeyframe(Angle(degrees: -50), duration: 0.08)
SpringKeyframe(Angle.zero, duration: 0.5, spring: .bouncy)
}
}
}
}
}
struct ImageView: View {
var body: some View {
Image(systemName: "apple.logo")
.symbolVariant(.fill)
.foregroundStyle(.black)
.font(.system(size: 100))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment