带点的Swift动画线

时间:2018-11-14 10:16:12

标签: ios swift calayer uibezierpath cabasicanimation

我使用CAShapeLayer和连接到这些圆的多条线创建了多个圆(点)。然后,我为那些圈子设置动画。我想做的是为连接的线和点设置动画。但是,只有圆圈没有为线设置动画。我怎样才能做到这一点?有没有更新行位置的方法?`

`

 var points: [CAShapeLayer] = []

let positions: [CGPoint] = [CGPoint(x: 70, y: 100),
                            CGPoint(x: 140, y: 100),
                            CGPoint(x: 210, y: 100),
                            CGPoint(x: 70, y: 200),
                            CGPoint(x: 140, y: 200),
                            CGPoint(x: 210, y: 200)]


var lines:[CAShapeLayer] = []

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    createPoints()
}

override func viewDidLoad() {
    super.viewDidLoad()
  }





func createPoints(){

    for (index,position) in positions.enumerated() {
        let point = CAShapeLayer()
        point.path = UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: 10, height: 10), cornerRadius: 5).cgPath
        point.frame = CGRect(x: position.x, y: position.y, width: 10, height: 10)

        point.fillColor = UIColor.red.cgColor
        points.append(point)

        view.layer.addSublayer(points[index])
     }
        animatePosition(point: points[0])

        drawLines()
}

func drawLines(){
    for (index,_) in positions.enumerated() {
        let path = UIBezierPath()

             //Not completed
            //set line's start position to dots position
            path.move(to: points[index].position)

            //set line's end position to dots position
            path.addLine(to: points[index+1].position)

        let line = CAShapeLayer()
        line.fillColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 0).cgColor
        line.strokeColor = #colorLiteral(red: 1, green: 0, blue: 0, alpha: 1).cgColor
        line.lineWidth = 1
        line.strokeStart = 0
        line.path = path.cgPath
        lines.append(line)
        view.layer.addSublayer(line)
    }
}



func animatePosition(point: CAShapeLayer) {

    let animation = CABasicAnimation(keyPath: "position")

    animation.fromValue = [10, 10 ]
    animation.toValue = [100, 100]
    animation.autoreverses = true
    animation.repeatCount = .infinity
    animation.isAdditive = true

    point.add(animation, forKey: "pointStart")
   // line.add(animation, forKey: "positionLine")
    self.view.setNeedsLayout()

}

enter image description here

我想要的是这样的东西: enter image description here

0 个答案:

没有答案