我需要沿着圆角矩形创建具有恒定长度的线动画。
因此,我在创建所需的BezierPath UIBezierPath(roundedRect: CGRect(x: 50, y: 50, width: 100, height: 100), cornerRadius: 5)
之后停止了工作,因此下一步我需要使用CAKeyframeAnimation
沿该路径设置宽度为45的线动画
有人可以帮我吗?
答案 0 :(得分:1)
那好吧。使用破折号代替开始/结束。建议使用this repo 计算cgPath长度以制作所需的图案。
let rectangle = UIView(frame: CGRect(x: 0, y: 0, width: 500, height: 500))
rectangle.clipsToBounds = true
rectangle.backgroundColor = .blue
rectangle.layer.cornerRadius = 50
let path = UIBezierPath(roundedRect: rectangle.bounds, cornerRadius: 50)
let shape = CAShapeLayer()
shape.path = path.cgPath
shape.lineWidth = 10
shape.strokeColor = UIColor.red.cgColor
shape.fillColor = UIColor.clear.cgColor
let length = path.cgPath.length
shape.lineDashPattern = [NSNumber(value: 45), NSNumber(value: Float(length - 45))]
rectangle.layer.addSublayer(shape)
let animation = CABasicAnimation(keyPath: "lineDashPhase")
animation.fromValue = 0
animation.toValue = length //-length to run animation clock-wise
animation.repeatCount = .infinity
animation.duration = 10
shape.add(animation, forKey: "MyAnimation")
PlaygroundPage.current.liveView = rectangle