2

enter image description here

Here is my code to draw dashed line

func drawLine() {

    let shapeLayer = CAShapeLayer()
    shapeLayer.bounds = viewDraw.bounds
    shapeLayer.position = CGPoint(x: viewDraw.bounds.width/2, y: viewDraw.bounds.height/2)
    shapeLayer.fillColor = nil
    shapeLayer.strokeColor = ColorConstants.ThemeColor.cgColor
    shapeLayer.lineWidth = 3
    shapeLayer.lineJoin = CAShapeLayerLineJoin.round // Updated in swift 4.2
    shapeLayer.lineDashPattern = [10]

    let path = UIBezierPath(roundedRect: viewDraw.bounds, cornerRadius: viewDraw.bounds.size.height/2)
    shapeLayer.path = path.cgPath

    viewDraw.layer.addSublayer(shapeLayer)

    let animation = CABasicAnimation(keyPath: "strokeEnd")
    animation.fromValue = 0
    animation.duration = 1
    shapeLayer.add(animation, forKey: "MyAnimation")
}

Now as per my screenshot I want to animate blue dot to red dot within that dashed line infinite time. When blue dot reaches red dot then it will start again with blue dot points.

Note: This whole screen is dynamic so, Line draw is also dynamic according to screen height

Any help would be appreciated

Bhavin Ramani
  • 3,221
  • 5
  • 30
  • 41
Jitendra Modi
  • 2,344
  • 12
  • 34

1 Answers1

1

You are almost there

Now you have to add animation using CAKeyframeAnimation which has property path where you can pass the path where you want to animate

here is working sample code

func drawLine() {

    let shapeLayer = CAShapeLayer()
    shapeLayer.bounds = self.view.bounds
    shapeLayer.position = CGPoint(x: self.view.bounds.width/2, y: self.view.bounds.height/2)
    shapeLayer.fillColor = nil
    shapeLayer.strokeColor = UIColor.red.cgColor
    shapeLayer.lineWidth = 3
    shapeLayer.lineJoin = CAShapeLayerLineJoin.round // Updated in swift 4.2
    shapeLayer.lineDashPattern = [10]

    let path = UIBezierPath(roundedRect: self.view.bounds, cornerRadius: self.view.bounds.size.height/2)
    shapeLayer.path = path.cgPath

    self.view.layer.addSublayer(shapeLayer)

    let animation1 = CABasicAnimation(keyPath: "strokeEnd")
    animation1.fromValue = 0
    animation1.duration = 1
    shapeLayer.add(animation1, forKey: "MyAnimation")

    // Create  squareView and add animation 
    let animation = CAKeyframeAnimation(keyPath: #keyPath(CALayer.position))
    animation.duration = 1
    animation.repeatCount = MAXFLOAT
    animation.path = path.cgPath

    let squareView = UIView()

   // Don't worry about x,y and width and height it will not affect the animation 
    squareView.frame = CGRect(x: 0, y: 0, width: 50, height: 50)
    squareView.backgroundColor = .lightGray
    view.addSubview(squareView)
    // You can also pass any unique string value for key
    squareView.layer.add(animation, forKey: nil)

}

You can see this tutorial for more help http://mathewsanders.com/animations-in-swift-part-two/

Prashant Tukadiya
  • 15,838
  • 4
  • 62
  • 98