ios - 为 UIBezierPath 创建旋转动画

标签 ios swift uikit uibezierpath cabasicanimation

<分区>

我有一个 CAShapeLayer,它是一个以我的 View Controller 的主视图为中心的圆。

看起来像这样:

CAShapeLayer (Circle)

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

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)
    }
}

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

This is what it looks like

非常感谢任何帮助!

最佳答案

而不是动画旋转,动画 lineDashPhase CAShapeLayer

的属性
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)
    }
}

enter image description here

关于ios - 为 UIBezierPath 创建旋转动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56363046/

相关文章:

ios - 使用 AudioKit 将麦克风输入的声音实时转换为音符

ios - 为UIImageView中的图像提供特效

ios - 如何在不花时间使用 Swift 的情况下从 iPhone 获取所有包含图像的相册?

ios - 将 float View (即静态和固定)添加到 UITableViewController

ios - 在 iOS 通知内容扩展中关闭键盘

iOS 谷歌原生广告不可点击

ios - 用于生产应用程序的内存中的 Realm 文件

ios - 点击时将标签文本设置为粗体

ios - Container View 好像有 UINavigationBar 一样被下推?

ios - CABasicAnimation 起源于右上角而不是中心