当视图重新进入前景时,继续绘制CAShapeLayer?

时间:2016-12-31 17:56:28

标签: ios swift cashapelayer

  func makeACircle(circle: UIView, stokeStart: Double, duration: Double){


        var progressCircle = CAShapeLayer();

        let centerPoint = CGPoint (x: circle.bounds.width / 2, y: circle.bounds.width / 2);
        let circleRadius : CGFloat = circle.bounds.width / 2

        var circlePath = UIBezierPath(arcCenter: centerPoint, radius: circleRadius, startAngle: CGFloat(-0.5 * M_PI), endAngle: CGFloat(1.5 * M_PI), clockwise: true    );

        progressCircle = CAShapeLayer ();
        progressCircle.path = circlePath.cgPath;
        progressCircle.strokeColor = UIColor.white.cgColor;
        progressCircle.fillColor = UIColor.clear.cgColor;
        progressCircle.lineWidth = 10;
        progressCircle.strokeStart = 0;
        progressCircle.strokeEnd = 1;
        progressCircle.borderWidth = 1
        progressCircle.borderColor = UIColor.black.cgColor

        circle.layer.addSublayer(progressCircle);
       // progressCircle.clipsToBounds = false
        self.view.addSubview(circle)

        let animation = CABasicAnimation(keyPath: "strokeEnd")

        // Set the animation duration appropriately
        animation.duration = duration

        // Animate from 0 (no circle) to 1 (full circle)
        animation.fromValue = stokeStart
        animation.toValue = 1

        // Do a linear animation (i.e. the speed of the animation stays the same)
        animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)

        // Set the circleLayer's strokeEnd property to 1.0 now so that it's the
        // right value when the animation ends.
        progressCircle.strokeEnd = 1.0

        // Do the actual animation
        progressCircle.add(animation, forKey: "animateCircle")

    }

我正在用上面的代码画圈子。它围绕屏幕上的按钮绘制一个圆圈,表示自创建按钮以来经过的时间。此代码有效,但当我进入主屏幕并返回时,无论剩余多少时间,屏幕上的所有圆圈都会完全填满。如果在应用程序中,我然后切换到另一个页面,然后回来,它修复它。

我在此firebase查询中调用makeACircle

 currentUserRef?.child("invitedToPosts").queryOrdered(byChild: "timestamp").queryStarting(atValue: cutoff).observe(.childAdded) { (snapshot: FIRDataSnapshot) in 

一旦我有足够的关于按钮的信息,我按下按钮,然后调用makeACircle。

当我从主页加载时,有关如何阻止圆圈不会出现在中途的任何想法吗?

1 个答案:

答案 0 :(得分:0)

暂停动画时,

  • 查看presentation layer并保存其strokeEnd

  • 您需要停止动画,这样做。您可能希望从表示层的值中设置strokeEnd,以避免任何不和谐的变化。

  • 查看自您开始动画以来经过了多长时间(例如,暂停时比较CACurrentMediaTime()与动画开始时的值比较),以便计算动画中剩余的时间

然后,当您重新展示图层时,您现在拥有fromValue的{​​{1}}以及余下的strokeEnd

另一件有用的事情是设置动画的duration,然后使用delegateanimationDidStop你的"正在进行中"动画成功完成时的状态变量(即如果nil为真)。