Created
May 17, 2022 17:20
-
-
Save hpinhal/91fc4b726e0e690338239d9c75b0c306 to your computer and use it in GitHub Desktop.
Lottie AnimationView for SwiftUI
This file contains 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 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) | |
} | |
} | |
} | |
} |
This file contains 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 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