如何使用 UIImage 数组为 CALayer 的内容 属性 设置动画?

How can I animate the contents property of a CALayer using an array of UIImages?

我想使用 CALayer 的内容 属性 为我放置在 UIImageView 上的蒙版制作动画。不幸的是我目前的实施 似乎只在数组的第一张和最后一张图像之间设置动画,而不在转换之间传递。有什么方法可以做到这一点,还是我应该看看其他东西,比如 CAReplicatorLayer?

这是我目前拥有的:

        let mask = CALayer()
        mask.frame = self.frame
        self.layer.mask = mask
        mask.contents = transitions.first?.cgImage

        let maskAnimation = CABasicAnimation(keyPath: "contents")
        maskAnimation.fromValue = transitions.first?.cgImage
        maskAnimation.toValue = transitions.last?.cgImage
        maskAnimation.duration = duration
        mask.contents = transitions.last
        mask.add(maskAnimation, forKey: "ContentsAnimation")

动画系统并不知道在第一张和最后一张图像之间插值意味着什么;你必须明确地告诉它。这正是关键帧动画的用途。

这是我的一个项目中形成这样一个动画的例子:

    let anim = CAKeyframeAnimation(keyPath:#keyPath(CALayer.contents))
    anim.values = self.images.map {[=10=].cgImage!}
    anim.keyTimes = [0.0, 0.25, 0.5, 0.75, 1.0]
    anim.calculationMode = kCAAnimationDiscrete
    anim.duration = 1.5

如您所见,我们有一组图像;它们是 UIImage,所以我必须导出它们的 CGImage 支持(我假设你的 transitions 是相似的)。 keyTimes数组用于将duration分成帧;由于动画的性质,我做这个划分有点奇怪,所以请随意修复时间以将持续时间 均匀地 .