以下代码用于根据保存的数据绘制动画图表。图表路径从其初始线变为数据库形状。这一切都充满了魅力。
然而,当我从另一个视图控制器输入新数据并转回时 我想恢复变形(现在从前一个最终形状到新形状)。数据被加载,最终的形状是应该的。 Hovewever路径和渐变动画永远不会动画。它只是瞬间处于最终位置。
事务完成块确实运行,所以我似乎无法弄清楚问题是什么。
非常感谢!
func fromToAnimPath(fromPath:CGMutablePath,toPath:CGMutablePath)->CAShapeLayer{
var graphShape:CAShapeLayer!
if statisticHolderView.layer.sublayers?.count == 2{
if let oldShape = statisticHolderView.layer.sublayers?.last{
print("reusing ols cashapelayer from statistichlderview")
graphShape = oldShape as! CAShapeLayer
}
}else{
print("creating layer for the first time")
graphShape = CAShapeLayer()
graphShape.fillColor = nil
graphShape.strokeColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1).cgColor
graphShape.lineWidth = 2
graphShape.path = fromPath
}
let gradiantAnim = CABasicAnimation.init(keyPath: "locations")
gradiantAnim.fromValue = [1,1,1]
gradiantAnim.toValue = [0.0,0.2,1]
gradiantAnim.duration = 0.5
gradiantAnim.timingFunction = CAMediaTimingFunction.init(name: kCAMediaTimingFunctionEaseOut)
let maskLayer = CAShapeLayer()
var gradiant:CAGradientLayer!
if ((graphShape.sublayers?.count) != nil) {
if let oldMask = graphShape.sublayers?.first{
gradiant = oldMask as! CAGradientLayer
print("Reusing gradiant")
}
}else{
gradiant = CAGradientLayer()
gradiant.startPoint = CGPoint.init(x: 0, y: 1)
gradiant.endPoint = CGPoint.init(x: 0, y: 0)
gradiant.colors = [#colorLiteral(red: 1, green: 1, blue: 1, alpha: 0).cgColor,#colorLiteral(red: 1, green: 1, blue: 1, alpha: 0).cgColor,#colorLiteral(red: 1, green: 1, blue: 1, alpha: 0.9).cgColor]
gradiant.locations=[0,0.2,1]
gradiant.backgroundColor = nil
gradiant.opacity = 0
}
maskLayer.frame = toPath.boundingBox
maskLayer.path = toPath
gradiant.frame = maskLayer.bounds
gradiant.mask = maskLayer
CATransaction.begin()
CATransaction.setCompletionBlock {
gradiant.opacity = 1
gradiant.add(gradiantAnim, forKey: nil)
}
let graphAnim = CABasicAnimation.init(keyPath: "path")
graphAnim.fromValue = graphShape.path
graphShape.path = toPath
graphAnim.toValue = graphShape.path
graphAnim.timingFunction = CAMediaTimingFunction.init(name: kCAMediaTimingFunctionEaseOut)
graphAnim.duration = 2.7
graphShape.add(graphAnim, forKey: nil)
if !didDrawInitialStartGraph{
print("inserted the graiant as a sublayer")
graphShape.insertSublayer(gradiant, at: 0)
}
CATransaction.commit()
pathCurve.addPath(toPath)
didDrawInitialStartGraph = true
return graphShape
}