dinis dinis - 1 year ago 134
Swift Question

Straight line path in swift

I need the help i have this code this is doing circular path but what i need is straight line i tried to do this but unsuccessful.

override func viewDidAppear(animated: Bool) {


let orbit = CAKeyframeAnimation(keyPath: "position")
var affineTransform = CGAffineTransformMakeRotation(0.0)
affineTransform = CGAffineTransformRotate(affineTransform, CGFloat(M_PI))
let circlePath = UIBezierPath(arcCenter: CGPoint(x: 150 - (100/2),y: 150 - (100/2)), radius: CGFloat(150), startAngle: CGFloat(0), endAngle:CGFloat(M_PI * 2), clockwise: true)

orbit.circlePath = path.CGPath
orbit.duration = 8
orbit.additive = true
orbit.repeatCount = 0.25
orbit.calculationMode = kCAAnimationPaced
orbit.rotationMode = kCAAnimationRotateAuto

moveobj.layer .addAnimation(orbit, forKey: "orbit")

and more one question how to do this disappear after finished to move.


Answer Source

You can easy do this using a CAShapeLayer.

    let line = CAShapeLayer()
    let linePath = UIBezierPath()
    linePath.move(to: CGPoint(x: 100, y: 100))
    linePath.addLine(to: CGPoint(x: 300, y: 300))
    line.path = linePath.cgPath
    line.strokeColor = UIColor.red.cgColor

First, create a CAShapeLayer. Second, create a UIBezierPath to define your line's path. Third, move the bezier path to a starting point. Fourth, add the ending point of the bezier path. fifth, apply the bezier path to the CAShapeLayer. Sixth, apply a stroke color so you can see the line when you add it as a sublayer. Finally, add it is a sublayer of the view.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download