多次调用相同的CABasicAnimation

时间:2016-04-06 03:46:37

标签: ios swift animation core-animation cabasicanimation

我目前有一个有效的黑客,但并不理想。我想在第一次调用它之前多次调用相同的动画。我正在使用delay函数,因为我不明白如何使用Core Animation正确实现我想要的内容。关于如何删除delay函数的任何想法都在这里调用并使用Core Animation方法/属性来获得相同的结果?

这是我的动画:

func animateCircle() {
    // The circle in its smallest size.
    let circlePath1 = UIBezierPath(arcCenter: self.center, radius: CGFloat(3), startAngle: CGFloat(0), endAngle:CGFloat(M_PI * 2), clockwise: true)

    // The circle in its largest size.
    let circlePath2 = UIBezierPath(arcCenter: self.center, radius: CGFloat(60), startAngle: CGFloat(0), endAngle:CGFloat(M_PI * 2), clockwise: true)

    // Configure the layer.
    let shapeLayer = CAShapeLayer()
    let green = UIColor(red: 0, green: 222, blue: 183, alpha: 100)
    shapeLayer.strokeColor = green.CGColor
    shapeLayer.fillColor = green.CGColor
    // This is the path that's visible when there'd be no animation.
    shapeLayer.path = circlePath1.CGPath
    self.layer.addSublayer(shapeLayer)

    // Animate the path.
    let pathAnimation = CABasicAnimation(keyPath: "path")
    pathAnimation.fromValue = circlePath1.CGPath
    pathAnimation.toValue = circlePath2.CGPath

    // Animate the alpha value.
    let alphaAnimation = CABasicAnimation(keyPath: "opacity")
    alphaAnimation.fromValue = 1
    alphaAnimation.toValue = 0

    // We want both animations to run together perfectly, so we
    // put them into an animation group.
    let group = CAAnimationGroup()
    group.animations = [pathAnimation, alphaAnimation]
    group.duration = 2.4
    group.repeatCount = FLT_MAX

    // Add the animation to the layer.
    shapeLayer.addAnimation(group, forKey:"sonar")
}

这就是我调用函数的方式:

  func delay(delay:Double, closure:()->()) {
    dispatch_after(
        dispatch_time(
            DISPATCH_TIME_NOW,
            Int64(delay * Double(NSEC_PER_SEC))
        ),
        dispatch_get_main_queue(), closure)
}

override func viewDidAppear(animated: Bool) {
    super.viewDidAppear(animated)

    animateCircle()

    delay(0.8) {
        self.animateCircle()
    }

    delay(1.6) {
        self.animateCircle()
    }
}

请注意delay的两种用法。我不想用这些。有什么想法吗?

0 个答案:

没有答案