3

I have to draw a straight line starting at 0,0 with some length and angle(from the top of view). Currently able to create a line by giving starting and ending points but instead of ending points, I have to use angle and length, any help?

Here is the code:

let path = UIBezierPath()
path.move(to: CGPoint(x: 0, y: 0))
path.addLine(to: CGPoint(x: 0+10, y: 0+10))

let shapeLayer = CAShapeLayer()
shapeLayer.path = path.cgPath
shapeLayer.strokeColor = UIColor.blue.cgColor
shapeLayer.lineWidth = 3.0

1 Answer 1

5

There are many ways to do this. One way is to start with a unit-length line along the Y axis. Rotate the line to the desired angle and scale it to the desired length. Example:

let angleInRadians: CGFloat = ...
let length: CGFloat = ...
let path = UIBezierPath()
path.move(to: .zero)
path.addLine(to: CGPoint(x: 0, y: 1))
path.apply(.init(rotationAngle: angleInRadians))
path.apply(.init(scaleX: length, y: length))

Another way is to use trigonometric functions directly to compute the non-origin endpoint of the line:

let angleInRadians: CGFloat = ...
let length: CGFloat = ...
let path = UIBezierPath()
path.move(to: .zero)
path.addLine(to: CGPoint(x: -sin(angleInRadians) * length, cos(angleInRadians) * length))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.