LottieInVideo

Render Lottie in video by AVFoundation

Stars
92

LottieInVideo

Render Lottie in video by AVFoundation

PAG vs Lottie

PAG Rendering vector animation in video, PAG is best for this job than lottie.

Lottie 3.1.0

master Lottie

Lottie 2.5.2

lottie-2.5.2 Lottie 2.5.2 Lottie Interpolate/CoreGraphics``layer

Lottie 1.0.4

Lottie 1.0.4 Lottie CAAnimation AVVideoComposition animationTool

    let instruction = AVMutableVideoCompositionInstruction()
    instruction.timeRange = CMTimeRange(start: CMTime.zero, duration: asset.duration)
    instruction.layerInstructions = [layerInstruction]
    videoComposition.instructions = [instruction]
    if let animationLayer = createStickerLayer(in: renderSize) {
        let parentLayer = CALayer()
        let videoLayer = CALayer()
        let contentLayer = CALayer()
        parentLayer.frame = CGRect(x: 0, y: 0, width: renderSize.width, height: renderSize.height)
        videoLayer.frame = CGRect(x: 0, y: 0, width: renderSize.width, height: renderSize.height)
        contentLayer.frame = CGRect(x: 0, y: 0, width: renderSize.width, height: renderSize.height)
        contentLayer.addSublayer(animationLayer)
        contentLayer.isGeometryFlipped = true
        parentLayer.addSublayer(videoLayer)
        parentLayer.addSublayer(contentLayer)
        videoComposition.animationTool = AVVideoCompositionCoreAnimationTool(postProcessingAsVideoLayer: videoLayer, in: parentLayer)
    }

    private func createStickerLayer(in size: CGSize) -> CALayer? {
        guard let sticker = sticker else { return nil }
        let layer = CALayer()
        layer.frame = CGRect(x: 0, y: 0, width: size.width, height: size.height)
        do {
            let animationData = try Data(contentsOf: URL(fileURLWithPath: sticker.url))
            if let animationJSON = try JSONSerialization.jsonObject(with: animationData, options: JSONSerialization.ReadingOptions(rawValue: UInt(0))) as? Dictionary<String, Any> {
                let animationLayer = LOTAnimationLayer.animation(fromJSON: animationJSON, customData: [], loop: false)!
                animationLayer.bounds = sticker.bounds(containerBounds: layer.bounds)
                animationLayer.position = sticker.center(containerBounds: layer.bounds)
                animationLayer.setAffineTransform(sticker.transform)
                animationLayer.beginTime = sticker.range.start.seconds
                animationLayer.duration = sticker.range.duration.seconds
                animationLayer.speed = sticker.speed
                layer.addSublayer(animationLayer)
            }
        } catch let e {
            print(e)
        }
        return layer
    }
Related Projects