【发布时间】:2017-11-14 06:46:21
【问题描述】:
我想捕捉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.asyc 和CAtransition.begin(), .setCompletionBlock, .commit(),但它们不起作用。
我应该怎么做才能得到我想要的?
【问题讨论】:
-
你不应该使用动画。而是使用计时器循环修改动画属性(不仅仅是简单的 for 循环!)。使用
render(in:)将图层内容绘制到图像上下文中。 -
@macmoonshine 谢谢你的回答!但我担心你的方式不适合我的项目。因为我的动画组使用 CAKeyframeAnimation 所以,它对于动画属性来说太复杂了。无论如何,谢谢你!顺便说一句,为什么一个简单的 for 循环不起作用?
-
CAAnimations 针对屏幕演示进行了优化。因此,它们的帧速率不均匀。不幸的是,如果你渲染中间的层,帧率会变差。
-
但是,我添加了一个适用于 CAAnimations 的答案。