【问题标题】:Create rotation animation for UIBezierPath [duplicate]为 UIBezierPath 创建旋转动画
【发布时间】:2019-05-29 14:34:20
【问题描述】:

我有一个 CAShapeLayer,它是一个以我的视图控制器的主视图中间为中心的圆。

看起来像这样:

我遇到的问题是,如果我尝试使用以下代码为旋转设置动画,它不会围绕圆心旋转,而是在其他地方旋转。

import UIKit

extension UIView {
    func addCircle(centerOfCircle: CGPoint, radius: CGFloat, startAngle: CGFloat?, endAngle: CGFloat?) {
        let circlePath = UIBezierPath(arcCenter: centerOfCircle, radius: radius, startAngle: startAngle ?? 0, endAngle: endAngle ?? CGFloat(Double.pi * 2), clockwise: true)

        let shapeLayer = CAShapeLayer()
        shapeLayer.path = circlePath.cgPath

        //change the fill color
        shapeLayer.fillColor = UIColor.clear.cgColor
        //you can change the stroke color
        shapeLayer.strokeColor = UIColor.red.cgColor

        shapeLayer.lineDashPattern = [1, 10]
        shapeLayer.lineCap = .round
        //you can change the line width
        shapeLayer.lineWidth = 3.0

        shapeLayer.anchorPoint = centerOfCircle

        let rotation : CABasicAnimation = CABasicAnimation(keyPath: "transform.rotation.z")
        rotation.toValue = NSNumber(value: Double.pi * 2)
        rotation.duration = 2
        rotation.isCumulative = true
        rotation.repeatCount = Float.greatestFiniteMagnitude



        shapeLayer.add(rotation, forKey: "rotationAnimation")

        self.layer.addSublayer(shapeLayer)
    }
}

然后我得到的是以下内容:

任何帮助将不胜感激!

【问题讨论】:

  • 我做到了@TejaNandamuri - 查看我的代码
  • 设置在 UIBezierPath 的中心。我应该把它设置在别的地方吗?
  • 不可能为贝塞尔路径设置动画,因为它只是对象遵循的路径。您必须为父视图设置动画
  • 没问题。您可以通过创建对象跟随的圆形贝塞尔路径来产生旋转错觉。

标签: ios swift uikit uibezierpath cabasicanimation


【解决方案1】:

不是为旋转设置动画,而是为CAShapeLayerlineDashPhase 属性设置动画

extension UIView {
    func addDashedCircle() {
        let circleLayer = CAShapeLayer()
        circleLayer.path = UIBezierPath(arcCenter: CGPoint(x: frame.size.width/2, y: frame.size.height/2),
                                        radius: frame.size.width/2,
                                        startAngle: 0,
                                        endAngle: .pi * 2,
                                        clockwise: true).cgPath
        circleLayer.lineWidth = 3.0
        circleLayer.strokeColor =  UIColor.red.cgColor
        circleLayer.fillColor = UIColor.white.cgColor
        circleLayer.lineJoin = .round
        circleLayer.lineDashPattern = [1,10]

        let animation = CABasicAnimation(keyPath: "lineDashPhase")
        animation.fromValue = 0
        animation.toValue = -11//1+10
        animation.duration = 1
        animation.repeatCount = .infinity
        circleLayer.add(animation, forKey: "line")

        layer.addSublayer(circleLayer)
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多