【发布时间】:2019-07-23 06:01:47
【问题描述】:
我正在尝试沿圆形路径为我的线形 CAShapeLayer 设置动画。我创建了线层的初始路径和最终路径,并将它们添加到 CABasicAnimation 的 from 和 to 值中。
然而动画并不是我所期待的。过去两天我都卡在这里了。
func getAllLayers() -> [CALayer]
{
var layers = []
let pointerEndPoint = CGPoint(x: xPointOfPointer , y: yPointOfPointer) // Final end point of pointer
let radius = 5
let pointerFinalPath = UIBezierPath()
pointerFinalPath.addArc(withCenter: circleCenter, radius: radius, startAngle: 0, endAngle:2 * CGFloat.pi, clockwise: false)
pointerFinalPath.move(to: circleCenter)
pointerFinalPath.addLine(to: endPoint)
pointerFinalPath.close()
let pointerPathLayer = CAShapeLayer()
pointerPathLayer.path = pointerFinalPath.cgPath
pointerPathLayer.lineWidth = 2
pointerPathLayer.fillColor = UIColor.black.cgColor
pointerPathLayer.strokeColor = UIColor.black.cgColor
layers.append(pointerPathLayer)
let pointerInitialBezierPath = UIBezierPath()
pointerInitialBezierPath.addArc(withCenter: circleCenter, radius: radius,startAngle: 0 , endAngle: 2 * CGFloat.pi , clockwise: false)
pointerInitialBezierPath.move(to: circleCenter)
pointerInitialBezierPath.addLine(to: CGPoint(x: circleCenter.x - 50 , y: centerY))
pointerInitialBezierPath.close()
let pointerInitialCGPath = pointerInitialBezierPath.cgPath
let pointerFinalCGPath = pointerFinalPath.cgPath
// Pointer Animation
let pointerAnimation = CABasicAnimation(keyPath: #keyPath(CAShapeLayer.path))
pointerAnimation.fromValue = pointerInitialCGPath
pointerAnimation.toValue = pointerFinalCGPath
pointerAnimation.duration = 0.5
pointerAnimation.isCumulative = true
pointerPathLayer.add(pointerAnimation, forKey: "Animation")
return layers
}
在堆栈溢出中搜索解决方案,但无法找到我的错误。我希望我的动画像时钟的指针一样移动。
请注意,针的长度会随着动画的进行而变化。我希望它保持恒定的长度,只希望我的针角改变。我将不胜感激。
编辑 1:如果我尝试 transform.rotation 动画,我会得到针旋转,但它发生在错误的中心点周围。
// Pointer Animation
let rotateAnimation = CABasicAnimation(keyPath: "transform.rotation")
rotateAnimation.fromValue = 0.0
rotateAnimation.toValue = angleOfActualValueinRad
rotateAnimation.duration = 2.0
pointerPathLayer.add(rotateAnimation, forKey: "Animation")
编辑 2:使用此链接查找我的 github 项目。 Animation Issue
【问题讨论】:
-
如果您更改
anchorPoint或pointerPathLayer并添加旋转动画,该怎么办? -
我用轮换代码发布答案。
-
@girish_pro 问题已更新
-
您需要设置锚点。检查我的答案。添加以下行。 pointerPathLayer.anchorPoint = CGPoint(x: 0.5, y: 0.5)
-
人们感谢您的帮助和时间。这里的问题是我没有为 CAShapeLayer 设置框架。这种做法是由于对 UIViews 使用约束而产生的。因此,正如@girish_pro 建议的那样,我通过正确地为每个 CAShapelayer 计算框架并在我的 CABasicAnimation 中应用角度值和角度值来修复它。
标签: ios swift cashapelayer cabasicanimation