Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to draw a straight line with the given length and angle?

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
like image 465
Syed Muhammad Yasir Avatar asked Dec 08 '25 10:12

Syed Muhammad Yasir


1 Answers

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))
like image 186
rob mayoff Avatar answered Dec 10 '25 23:12

rob mayoff