LoginSignup
0
0

【SwiftUI】Lottieを使ってアニメーションを簡単に実装してみた

Last updated at Posted at 2023-10-24

Lottieとは

アニメーションを記述したjsonファイルをプロジェクトに追加して呼び出すだけで簡単にアニメーションを実装できるライブラリです。アニメーションのjsonファイルは無料でダウンロードできるので気軽に実装できます。

LottieFiles

ここからダウンロードできます

Lottieのライブラリのリポジトリ

LottieViewを定義する

Lottieを導入したら、まずLottieViewを定義してViewで呼び出せるようにします。

少し前の記事でlet animationView = AnimationView().animation.named(name)と宣言されている場合がありますが、動かないようなのでLottieAnimationView(name: String)で宣言しています。(バージョンが更新された際に仕様が変更されたのかもしれません)

LottieView.swift
import Lottie
import SwiftUI

struct LottieView: UIViewRepresentable {
    
    var name: String
    let loopMode: LottieLoopMode
    
    func makeUIView(context: UIViewRepresentableContext<LottieView>) -> UIView {
        let view = UIView(frame: .zero)
        
        let animationView = LottieAnimationView(name: name)
        animationView.contentMode = .scaleAspectFit
        animationView.loopMode = loopMode
        animationView.play{ (finished) in
            
        }
        
        animationView.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(animationView)
        NSLayoutConstraint.activate([
            animationView.heightAnchor.constraint(equalTo: view.heightAnchor),
            animationView.widthAnchor.constraint(equalTo: view.widthAnchor)
        ])
        
        return view
    }
    
    func updateUIView(_ uiView: UIViewType, context: Context) {
        
    }
}

今回はloopModeだけをView側で変更できるようにしています。loopModeには以下の5種類があります。

/// Defines animation loop behavior
public enum LottieLoopMode {
  /// Animation is played once then stops.
  case playOnce
  /// Animation will loop from beginning to end until stopped.
  case loop
  /// Animation will play forward, then backwards and loop until stopped.
  case autoReverse
  /// Animation will loop from beginning to end up to defined amount of times.
  case `repeat`(Float)
  /// Animation will play forward, then backwards a defined amount of times.
  case repeatBackwards(Float)
}

Viewで呼び出す際は非常にシンプルで.frameで大きさも指定できます。

LottieView(name: "sample", loopMode: .playOnce)              
    .frame(width: 200, height: 200)

最後に

Lottieを使うことで簡単に高度なアニメーションを実装することができました。ちなみにAdobeのソフトでアニメーションを制作してjsonファイルとして出力すればオリジナルのアニメーションを制作することができるそうです。

参考リンク

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0