简体   繁体   English

如何绘制给定长度和角度的直线?

[英]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). 我必须绘制一条从0,0开始的直线,并带有一些长度和角度(从视图顶部开始)。 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. 一种方法是从沿Y轴的单位长度线开始。 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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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