CAGroupAnimation 不显示动画。单独添加时动画效果很好

CAGroupAnimation does not show animations. Animations work fine when added separately

我正在使用 Swift 和核心动画实现一个简单的 activity 指标。核心动画循环仅包含两个动画。当我将它们直接添加到图层时,它们工作得很好。当我将它们添加为 CAAnimationGroup 时,什么也没有发生。我对这种行为感到非常困惑,并且我已经检查了关于 CAAnimationGroup 的所有关于 Whosebug 的问题,网络上的所有教程,并多次阅读了官方文档。我不知道发生了什么事。请帮忙。

动画:

let anim1 = CABasicAnimation(keyPath: "strokeEnd")
anim1.fromValue = 0
anim1.toValue = 1.0
anim1.duration = 2.0
anim1.beginTime = CACurrentMediaTime()

let anim2 = CABasicAnimation(keyPath:"strokeStart")
anim2.fromValue = 0
anim2.toValue = 1.0
anim2.duration = 2.0
anim2.beginTime = CACurrentMediaTime() + 2.0

这完全符合预期:

shapeLayer.addAnimation(anim1, forKey:nil)
shapeLayer.addAnimation(anim2, forKey:nil)

这对我的层没有任何作用:

let group = CAAnimationGroup()
group.animations = [anim1, anim2]
group.duration = 4.0
shapeLayer.addAnimation(group, forKey: nil)

我制作了一个用于 Playground 的简短演示片段:https://gist.github.com/anonymous/6021295eab4e00b813ce. Please see for yourself and help me solve this. (In case you're not sure how to use Playground for prototyping animations: http://possiblemobile.com/2015/03/prototyping-uiview-animations-swift-playground/)

这样试试,貌似 CACurrentMediaTime() + 2.0 导致了问题

import UIKit
import XCPlayground
let view = UIView(frame: CGRect(x: 0, y: 0, width: 500, height: 500))
let shapeLayer = CAShapeLayer()
let size:CGFloat = 52
let rect = CGRect(x: view.bounds.midX - size/2, y: view.bounds.midY-size/2, width: size, height: size)
shapeLayer.path = UIBezierPath(ovalInRect: rect).CGPath
shapeLayer.fillColor = UIColor.clearColor().CGColor
shapeLayer.strokeColor = UIColor.redColor().CGColor
shapeLayer.lineWidth = 3
shapeLayer.strokeStart = 0
shapeLayer.strokeEnd = 0
view.layer.addSublayer(shapeLayer)
XCPShowView("view", view)

let beginTime = CACurrentMediaTime()
let anim1 = CABasicAnimation(keyPath: "strokeEnd")
anim1.fromValue = 0
anim1.toValue = 1
anim1.duration = 2

let anim2 = CABasicAnimation(keyPath:"strokeEnd")
anim2.fromValue = 1
anim2.toValue = 0
anim2.duration = 2
anim2.beginTime =  2

let group = CAAnimationGroup()
group.duration = 4.0
group.removedOnCompletion = true
group.animations = [anim1, anim2]
//shapeLayer.addAnimation(anim1, forKey:nil)
//shapeLayer.addAnimation(anim2, forKey:nil)
shapeLayer.addAnimation(group, forKey: nil)

@MDB983 的回答看起来可行,但没有解释原因。

当您将动画直接添加到图层时,它的开始时间基于当前媒体时间。

当您将动画添加到动画组时,它们的 "local time" 就是动画组。动画组中 0 的开始时间是组的开始,1.0 的开始时间是整个动画组的 1 秒,等等。当您将动画添加到动画组时,将开始时间更改为从零开始,不是从 CACurrentMediaTime().

开始

我知道这是一个老问题,但我在 swift 4 中对动画组做了同样的事情。我错过的是为 CAAnimationGroup 本身指定 beginTime(我假设子动画会跟随他们的开始时间)。默认情况下,CAAnimationGroup

的 beginTime 为 0.0
let group = CAAnimationGroup()
group.beginTime = CACurrentMediaTime() + delay
group.duration = 4.0
group.removedOnCompletion = true
group.animations = [anim1, anim2]