我正在使用Swift和Core Animation实现一个简单的活动指示器。核心动画循环仅包含两个动画。当我直接将它们添加到图层时,它们可以完美工作。当我将它们添加为CAAnimationGroup时,什么都没有发生。我对这种行为完全感到困惑,并且我已经检查了有关CAAnimationGroup的所有关于stackoverflow的问题,网络上的所有教程,并多次阅读了官方文档。我不知道发生了什么事。请帮助。
动画:
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。请亲自看看,并帮助我解决这个问题。 (以防您不确定如何使用Playground制作原型动画的情况:http://possiblemobile.com/2015/03/prototyping-uiview-animations-swift-playground/)
[将动画添加到动画组时,它们的“本地时间”是动画组。动画组中的开始时间为0是该组的开始,而动画组中的beginTime为1.0是1秒,以此类推。以此类推。将动画添加到动画组中时,您的开始时间应从零开始,不是从CACurrentMediaTime()
开始。
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)
let group = CAAnimationGroup()
group.beginTime = CACurrentMediaTime() + delay
group.duration = 4.0
group.removedOnCompletion = true
group.animations = [anim1, anim2]