如何捕获CAAnimation

时间:2017-11-14 06:46:22

标签: swift calayer

我希望在CALayer上捕捉动画的每一帧,以生成mp4电影文件。

所以,我在下面写了代码。

frames是动画中的总帧数,frameTime是1/60秒,animationLayer已添加UIImageView

for i in 0...(frames - 1) {

    //add the animation on specified frame to the CALayer
    animationGroup.speed = 0
    animationGroup.timeOffset = frameTime * i
    animationLayer.add(animationGroup, forKey: "morph")

    //capture the frame of the animation.
    UIGraphicsBeginImageContextWithOptions(drawView.bounds.size, true, 0.0)
    drawView.drawHierarchy(in: drawView.bounds, afterScreenUpdates: true)
    uiImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    uiImage = globalFunc.resizeUIImage(uiImage, scale, 400)
    cgImage = uiImage.cgImage!

    //add the captured image to movie file.
    movieCreator.create(image: cgImage)

    animationLayer.removeAnimation(forKey: "moprh")
}

此代码不起作用。

不显示每个帧的图像,并且创建了电影文件,但没有动画。

我在上面的代码中尝试了DispatchQueue.main.asycCAtransition.begin(), .setCompletionBlock, .commit(),但它们无效。

我该怎么做才能得到我想要的东西?

1 个答案:

答案 0 :(得分:0)

您不应将视图层次结构绘制到图像上下文中。您应该像这样渲染表示层:

if let presentationLayer = drawView.layer.presentation() {
    presentationLayer.render(in: context)
}

表示层表示当前在屏幕上绘制的图层内容。