Created
May 3, 2024 20:08
-
-
Save davidsteppenbeck/20d16160b6b037b193a308349ff36a18 to your computer and use it in GitHub Desktop.
Keyframe Animation Example in SwiftUI
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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