LottieUI

LottieUI runing on both iOS and macOS

LottieUI 允许您在 SwiftUI 中使用令人愉悦的 Lottie 动画,而无需放弃熟悉的声明式 API 或动画框架中强大的自定义设置。

☑️ 要求

🧑‍💻 用法

要显示来自本地 Lottie JSON 文件的动画,请使用 LottieView 组件。

LottieView("MyAnimation")

如果您的 JSON 存储在项目外部的另一个 bundle 中,您可以指定 Bundle 以从中加载动画,或者提供动画文件所在的文件路径。

// Loads an animation from the provided bundle
LottieView("MyAnimation", bundle: DesignSystem.Bundle.main)
// Loads an animation file from the provided path
LottieView(path: "/path/to/animation.json")

🛰 远程动画

对于远程动画,LottieUI 提供了 AsyncLottieView,它会尝试从远程 URL 下载动画并在成功时显示它。 您还可以提供在下载进行中或下载失败时显示的视图。

let url = URL(string: "https://assets3.lottiefiles.com/packages/lf20_hbdelex6.json")!

AsyncLottieView(url: url) { phase in
    switch phase {
    case .loading:
        ProgressView()
    case .error:
        ErrorView
    case .success(let lottieView):
        lottieView
    }
}

🚀 功能

LottieView 允许您通过一组可以应用于 LottieView 的修饰符来控制动画。

⏯ 播放

默认情况下,您的动画将自动开始播放。 要控制动画是否应该播放,请使用 .play(_:) 修饰符。

struct ContentView: View {
    @State var isPlaying: Bool = true
    
    var body: some View {
        LottieView("MyAnimation")
            .play(isPlaying)
    }
}

Playback modifier demo

🔁 循环模式

要设置动画的循环模式,请使用 .loopMode(_:)

struct ContentView: View {
    var body: some View {
        LottieView("MyAnimation")
            .loopMode(.loop)
    }
}

Speed modifier demo

🖼 当前帧和进度

要观察动画中显示的当前帧并根据它执行操作,请使用 .onFrame(_:)

警告 要使用帧/进度观察器,动画必须使用 .mainThread 渲染引擎。 这可以通过使用 .renderingEngine(_:) 方法来设置。

struct ContentView: View {
    var body: some View {
        LottieView("MyAnimation")
            .renderingEngine(.mainThread)
            .onFrame { _ in
                // Perform action based on current frame
            }
    }
}

要观察进度,请使用 .onProgress(_:)

struct ContentView: View {
    var body: some View {
        LottieView("MyAnimation")
            .renderingEngine(.mainThread)
            .onProgress { _ in
                // Perform action based on current progress
            }
    }
}

Progress Observer modifier demo

🏃 速度

要设置动画的速度,请使用 .speed(_:)

struct ContentView: View {
    var body: some View {
        LottieView("MyAnimation")
            .speed(2.0)
    }
}

Speed modifier demo

渲染引擎

LottieUI 还支持 Lottie 3.4.0 中引入的新的 RenderingEngine,它可以大大降低显示兼容动画时的 CPU 使用率。

默认情况下,LottieUI 使用 .automatic,如果动画兼容,它将自动应用新的渲染引擎,但您可以使用 .renderingEngine(_:) 修饰符覆盖它。

LottieView("MyAnimation")
    .renderingEngine(.coreAnimation)

Rendering Engine modifier demo

还有许多其他选项可用,例如

有关更多信息,请查看每个公共组件和修饰符中包含的文档。

🛠 安装

Swift Package Manager

在项目的 Package.swift 文件中,将 LottieUI 添加为依赖项。

.package(name: "LottieUI", url: "https://github.com/tfmart/LottieUI", from: "1.0.0")