简体   繁体   English

如何使用UIImages数组为CALayer的content属性设置动画?

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

I'd like to animate a mask I placed on a UIImageView using the contents property of the CALayer . 我想使用CALayer的contents属性对放置在UIImageView上的蒙版进行动画处理。 Unfortunately my current implementation only seems to animate between the first and last images of the array without passing between the transitions. 不幸的是,我当前的实现似乎只是在数组的第一张和最后一张图像之间设置动画,而没有在过渡之间传递。 Is there any way of achieving this, or should I be looking at other things like CAReplicatorLayer ? 有什么办法可以做到这一点,还是我应该看看其他类似CAReplicatorLayer东西?

Here's what I currently have: 这是我目前拥有的:

        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")

The animation system doesn't magically know what it means to interpolate between the first and last images; 动画系统并不神奇地知道在第一张和最后一张图像之间进行插补的含义。 you have to tell it, explicitly. 您必须明确地告诉它。 That is exactly what a keyframe animation is for. 这正是关键帧动画的用途。

Here's an example of forming such an animation, from a project of mine: 这是一个由我的项目构成的动画的示例:

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

As you can see, we have an array of images; 如您所见,我们有一系列图像; they are UIImages, so I have to derive their CGImage backing (I assume your transitions is similar). 它们是UIImages,因此我必须获得其CGImage的支持(我假设您的transitions是相似的)。 The keyTimes array is used to divide up the duration into frames; keyTimes数组用于将duration分为几帧; I'm doing this division a little oddly because of the nature of my animation, so feel free to fix the times to divide the duration evenly . 由于动画的性质,我在进行这种划分时有些奇怪,因此请随时确定时间以平均划分持续时间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM