iOS Swift如何同步图表绘制的线条,渐变和圆形动画?

时间:2019-03-22 19:03:23

标签: ios swift animation core-graphics core-animation

我尝试同步图表线,圆和渐变的动画。

这是花式图表gif,动画不同步:/ chart animation

运行所有动画代码:

        CATransaction.begin()
        CATransaction.setAnimationDuration(5.0)
        CATransaction.setAnimationTimingFunction(CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut))
        self?.animateLineDrawing()
        self?.animateGradient()
        self?.animateCircle()
        CATransaction.commit()

画线动画:

    let animation = CABasicAnimation(keyPath: "strokeEnd")
    animation.fromValue = 0.0
    animation.toValue = 1.0
    lineShapeLayer.add(animation, forKey: "drawLineAnimation")
    lineShapeLayer.path = curvedPath.cgPath

我有gradientContainer图层,其中gradientLayer为子图层。我只将容器蒙版层移到渐变层上:

    let animationPath = UIBezierPath(rect: CGRect(x: firstPoint.x,
                                         y: chartRect.origin.y,
                                         width: 0,
                                         height: chartRect.height))
    let animation = CABasicAnimation(keyPath: "path")
    animation.fromValue = animationPath.cgPath
    animation.toValue = UIBezierPath(rect: CGRect(x: firstPoint.x,
                               y: chartRect.origin.y,
                               width: chartRect.width,
                               height: chartRect.height)).cgPath
    animation.isRemovedOnCompletion = false
    animation.fillMode = CAMediaTimingFillMode.forwards
    animation.delegate = self
    gradientContainerLayer.mask?.add(animation, forKey: nil)

在图表路径上圈出动画:

    let animation = CAKeyframeAnimation(keyPath: "position")
    animation.path = viewModel.curvedPath(frame)?.cgPath
    animation.delegate = self
    circleLayer.add(animation, forKey: nil)
  1. 渐变动画无法同步,因为路径上的距离不同于直线,有人知道如何同步吗?

  2. 为什么圆形动画的计时不等于直线动画?看起来动画的开始和结束是相等的,所以计时功能不同,为什么?

1 个答案:

答案 0 :(得分:1)

CAKeyframeAnimation上全部切换而不使用基本动画和属性动画。我个人发现它们通常更容易调整和更灵活。

计算每个元素在相同时间点处在相同x坐标中的位置。
您应该考虑在每个兴趣点上至少添加1个点(y坐标的减小和增加之间的变化),以免削减局部极值。