Skip to content

Instantly share code, notes, and snippets.

@hpinhal
Created May 17, 2022 17:20
Show Gist options
  • Save hpinhal/91fc4b726e0e690338239d9c75b0c306 to your computer and use it in GitHub Desktop.
Save hpinhal/91fc4b726e0e690338239d9c75b0c306 to your computer and use it in GitHub Desktop.
Lottie AnimationView for SwiftUI
import Lottie
import SwiftUI
struct ContentView: View {
var body: some View {
ZStack {
GeometryReader { reader in
LottieAnimationView(.named("drinks"))
.animationSpeed(0.5)
.frame(maxWidth: reader.size.width, maxHeight: reader.size.height)
}
}
}
}
import Lottie
import SwiftUI
struct LottieAnimationView: UIViewRepresentable {
private let animation: Lottie.Animation?
private var animationSpeed: CGFloat = 1
private var backgroundBehavior: Lottie.LottieBackgroundBehavior = .pauseAndRestore
private var contentMode: UIView.ContentMode = .scaleAspectFit
private var loopMode: Lottie.LottieLoopMode = .loop
init(_ animation: Lottie.Animation?) {
self.animation = animation
}
func makeUIView(context: Context) -> AnimationView {
AnimationView()
}
func updateUIView(_ view: AnimationView, context: Context) {
view.animation = animation
view.animationSpeed = animationSpeed
view.backgroundBehavior = backgroundBehavior
view.contentMode = contentMode
view.loopMode = loopMode
view.play()
}
func backgroundBehavior(_ behavior: Lottie.LottieBackgroundBehavior) -> Self {
var view = self
view.backgroundBehavior = behavior
return view
}
func animationSpeed(_ speed: CGFloat) -> Self {
var view = self
view.animationSpeed = speed
return view
}
func contentMode(_ mode: UIView.ContentMode) -> Self {
var view = self
view.contentMode = mode
return view
}
func loopMode(_ mode: Lottie.LottieLoopMode) -> Self {
var view = self
view.loopMode = mode
return view
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment