2015-06-11 58 views
2

我正在使用Swift和Core Animation實現一個簡單的活動指示器。核心動畫循環由兩個動畫組成。當我直接將它們添加到圖層時,它們完美地工作。當我將它們添加爲CAAnimationGroup時,根本沒有任何事情發生。我完全被這種行爲所困惑,並且我已經檢查了關於CAAnimationGroup的所有stackoverflow的問題,網絡上的所有教程以及多次閱讀官方文檔。我無法弄清楚發生了什麼事。請幫忙。CAGroupAnimation不顯示動畫。當單獨添加動畫時,動畫工作正常

動畫:

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) 

我做了一個簡短的演示片段中使用在遊樂場:https://gist.github.com/anonymous/6021295eab4e00b813ce。請親自看看並幫我解決這個問題。 (如果你不知道如何使用遊樂場爲原型的動畫:http://possiblemobile.com/2015/03/prototyping-uiview-animations-swift-playground/

回答

3

@ MDB983的答案看起來會起作用,但不能解釋原因。

將動畫直接添加到圖層時,開始時間基於當前媒體時間。

當您將動畫添加到動畫組中時,其「當地時間」是動畫組。動畫組中的開始時間爲0是該組的開始,並且1.0的beginTime爲整個動畫組中的1秒等。向動畫組添加動畫時,將開始時間更改爲從零開始,不是從CACurrentMediaTime()開始。

+0

這是完美的,非常感謝!現在清楚發生了什麼事情。 – user5000952

0

嘗試這種方式,看似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) 
+0

是的!非常感謝! – user5000952