SwiftUI에서 Lottie 애니메이션 사용하기

Jerry Uhm·2023년 2월 20일
0
post-thumbnail

Lottie란?

  • Airbnb에서 만든 벡터기반의 애니메이션을 실시간으로 렌더링하는 라이브러리
  • 애니메이션의 재생,정지,크기조절,속도조절등의 자유자재로 핸들링이 가능하다.
  • https://github.com/airbnb/lottie-ios

Lottie 사용하기

  • lottie는 cocoapods, swift package등으로 쉽게 적용하여 사용 가능
  • pod 'lottie-ios'
  • 애니메이션 데이타는 https://lottiefiles.com 에서 쉽게 다운로드 가능

SwiftUI Lottie 소스

  • Lottie는 UIKit기반으로 구현된 라이브러리로써 SwiftUI에서 사용하기 위해서는 UIViewRepresentable 프로토콜을 이용하여 wrapping하여 사용할 수 있다.
import SwiftUI
import Lottie
import UIKit

struct LottieView: UIViewRepresentable {
    var fileName: String
    var animationView = AnimationView()
    var backgroundBehavior: LottieBackgroundBehavior = .stop
    var loopMode: LottieLoopMode = .playOnce
    var autoPlay: Bool = false
    
    //makeCoordinator를 구현하여 제약사항을 구현합니다.
    func makeCoordinator() -> Coordinator {
        Coordinator(self)
    }
    
    class Coordinator: NSObject {
        var parent: LottieView
        
        init(_ animationView: LottieView) {
            //frame을 LottieView로 할당합니다.
            self.parent = animationView
            super.init()
        }
    }
    
    func makeUIView(context: UIViewRepresentableContext<LottieView>) -> UIView {
        let view = UIView(frame: .zero)
        
        animationView.animation = Animation.named(fileName)
        animationView.contentMode = .scaleAspectFit
        animationView.loopMode = .loop
        // 다른뷰로 이동했거나 백그라운드로 내려갔을때의 옵션 (기본값은 .pause)
        animationView.backgroundBehavior = backgroundBehavior
        
        if (autoPlay) {
            animationView.play()
        }
        animationView.loopMode = loopMode
        
        //컨테이너의 너비와 높이를 자동으로 지정할 수 있도록
        animationView.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(animationView)
        
        NSLayoutConstraint.activate([
            animationView.widthAnchor.constraint(equalTo: view.widthAnchor),
            animationView.heightAnchor.constraint(equalTo: view.heightAnchor)
        ])
        
        return view
    }
    
    //동적으로 애니메이션 변경을 할때
    func updateUIView(_ uiView: UIView, context: UIViewRepresentableContext<LottieView>) {
        
        //변경된 json으로 애니메이션을 변경합니다.
        //animationView.animation = Animation.named(fileName)
        //animationView.play()
    }
    
    func playAnimation() {
        animationView.play()
    }
    
    func stopAnimation() {
        animationView.stop()
    }
}

swiftui에서 기본적으로 lottie애니메이션을 사용하는 방법으로 swiftui에서는 간단한 코드로 쉽게 애미메이션 구현이 가능합니다.

애니메이션을 실행하는 부분은 다음과 같이 코드를 작성해 줍니다.

import SwiftUI

struct LottieAnim: View {
    let fileName: String
    
    var body: some View {
        VStack {
            LottieView(fileName: fileName,
                       backgroundBehavior: .pauseAndRestore,
                       loopMode: .loop,
                       autoPlay: true)
                .frame(width: 300, height: 300)
        }
        
    }
}

profile
ios 개발자 입니다.

0개의 댓글