【问题标题】:Line animation in rectangle with cornerRadius具有cornerRadius的矩形中的线条动画
【发布时间】:2019-06-11 07:29:53
【问题描述】:

我需要沿圆角矩形创建具有恒定长度的线条动画。 所以我在创建所需的 BezierPath UIBezierPath(roundedRect: CGRect(x: 50, y: 50, width: 100, height: 100), cornerRadius: 5) 后停止了,所以下一步我需要做的是使用 CAKeyframeAnimation 沿该路径设置宽度为 45 的动画线 有人可以帮我吗?

【问题讨论】:

  • 你想动画从头到尾的线条画吗?
  • 是的@RajeshKumarR,但问题是该行是该路径的 1/4 长度。另外我需要无限重复计数
  • 打赌你会在这里找到答案 - stackoverflow.com/questions/42978418/draw-line-animated
  • @Kirow 我正在使用CAKeyframeAnimation(keyPath: "strokeEnd")CAKeyframeAnimation(keyPath: "strokeStart")。主要问题是它看起来不像无穷大,它在strokeEnd = 0 时停止了,因为它不能大于 1

标签: swift animation cashapelayer cakeyframeanimation


【解决方案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

【讨论】:

    猜你喜欢
    • 2019-08-02
    • 2019-03-03
    • 2011-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-21
    • 2016-12-03
    • 1970-01-01
    相关资源
    最近更新 更多