带 cornerRadius 的矩形中的线动画
Line animation in rectangle with cornerRadius
我需要创建沿圆角矩形长度恒定的线条动画。
所以我在创建所需的 BezierPath UIBezierPath(roundedRect: CGRect(x: 50, y: 50, width: 100, height: 100), cornerRadius: 5)
后停止了,所以下一步我需要做的是使用 CAKeyframeAnimation
沿该路径设置宽度为 45 的动画线
有人可以帮我吗?
好的,那么。使用破折号模式而不是 start/end。建议使用 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
我需要创建沿圆角矩形长度恒定的线条动画。
所以我在创建所需的 BezierPath UIBezierPath(roundedRect: CGRect(x: 50, y: 50, width: 100, height: 100), cornerRadius: 5)
后停止了,所以下一步我需要做的是使用 CAKeyframeAnimation
沿该路径设置宽度为 45 的动画线
有人可以帮我吗?
好的,那么。使用破折号模式而不是 start/end。建议使用 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