Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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