问题添加 Lottie 动画子层捕获会话

问题描述

基本上,我目前执行以下操作以在 captureSession 顶部显示一个方块,但我想用 Lottie 动画替换该方块 - 无法理解如何放置和播放动画而不是显示静态方块:

captureSession.startRunning()

let scannerOverlayPreviewLayer = ScannerOverlayPreviewLayer(session: captureSession)
scannerOverlayPreviewLayer.frame = self.view.bounds
scannerOverlayPreviewLayer.maskSize = CGSize(width: 200,height: 200)
scannerOverlayPreviewLayer.backgroundColor = UIColor.black.withAlphaComponent(0.5).cgColor
scannerOverlayPreviewLayer.videoGravity = .resizeAspectFill
self.view.layer.addSublayer(scannerOverlayPreviewLayer)

动画:

private var animationView: AnimationView?
animationView = .init(name: "scan")
animationView!.frame = view.bounds
animationView!.contentMode = .scaleAspectFit
animationView!.loopMode = .loop
animationView!.animationSpeed = 0.5
view.addSubview(animationView!)
animationView!.play()

我的目的是将动画放置在屏幕中央。动画的大小也是宽:200,高:200。

解决方法

你是想把 Lottie 放在屏幕中间吗?
建议你先在中间做个view,然后在里面设置Lottie。

首先,在屏幕中间创建一个高度为 200,宽度为 200 的视图。

        let myView = UIView()
        self.view.addSubview(myView)
        
        myView.translatesAutoresizingMaskIntoConstraints = false

        myView.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true
        myView.centerYAnchor.constraint(equalTo: self.view.centerYAnchor).isActive = true
        myView.widthAnchor.constraint(equalToConstant: 200).isActive = true
        myView.heightAnchor.constraint(equalToConstant: 200).isActive = true

然后将 AnimationView 插入您创建的视图中。你可以用 Lottie 设置同样的东西。

       let animationView = AnimationView(name: "scan")
        
        animationView.frame = CGRect(x: 0,y: 0,width: myView.bounds.width,height: myView.bounds.height)