简体   繁体   中英

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

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM