swift - 计算打开 2d 路径
问题描述
我的屏幕上有一个 UIBezier 路径绘制,由 5 条不同的线组成。
[![在此处输入图片描述][1]][1]
我想要做的是计算任何两条线之间的角度差,以便我可以确定下一条线相对于最后一条线的方向。
我可以检测直线没问题。我遇到的问题是我无法区分在 x 轴上增加的线(向右走)和在 x 轴上减少的线(向左走)之间的区别
在这两种情况下,角度为 90。
理想的结果是“左”在 90 到 270 度之间,“右”在 270 到 90 度之间。
我的 Trig 生锈了,所以我怀疑我是否走在正确的轨道上。
这是我尝试过的
Struct 为我的线条建模
struct Line
{
var point1:CGPoint
var point2: CGPoint
var vector:CGVector {
get {
return CGVector(dx: point1.x - point2.x, dy: point1.y - point2.y)
}
}
}
画我的线
let line1 = Line(point1: CGPoint(x: 100, y: 300), point2: CGPoint(x: 100, y: 200))
let line2 = Line(point1: CGPoint(x: 100, y: 200), point2: CGPoint(x: 200, y: 200))
let line3 = Line(point1: CGPoint(x: 200, y: 200), point2: CGPoint(x: 200, y: 150))
let line4 = Line(point1: CGPoint(x: 200, y: 150), point2: CGPoint(x: 100, y: 150))
let line5 = Line(point1: CGPoint(x: 100, y: 150), point2: CGPoint(x: 100, y: 50))
lines = [line1,line2,line3,line4,line5]
let path = UIBezierPath()
for line in lines!{
path.move(to: CGPoint(x: line.point1.x, y: line.point1.y))
path.addLine(to: CGPoint(x:line.point2.x, y: line.point2.y))
}
let shapeLayer = CAShapeLayer()
shapeLayer.path = path.cgPath
shapeLayer.strokeColor = UIColor.blue.cgColor
shapeLayer.lineWidth = 3.0
testView.layer.addSublayer(shapeLayer)
计算方向
@IBAction func calculateAngles()
{
var i = 0
let count = lines!.count - 1
while i < count
{
let l1 = lines![i]
let slope = (l1.point2.y - l1.point1.y) / (l1.point2.x - l1.point1.x)
let theta1 = atan(slope)
let l2 = lines![i + 1]
let slope2 = (l2.point2.y - l2.point1.y) / (l2.point2.x - l2.point1.x)
let theta2 = atan(slope2)
let angleBetween = theta1 - theta2
print(rad2deg(Double(angleBetween)))
// - 90 , 90 , -90 , 90
// desired result 0 , 270 , 180 , 270
i += 1
}
}
解决方案
推荐阅读
- mysql - SQL如何过滤掉两位小数的值
- c - 返回意外的负值
- css - Tailwind React 中的边框间距
- c# - 如何使用 Angular 9 向 Http 请求添加自定义属性
- visual-studio - 如何在没有整个项目的情况下打开 .sln 文件?
- javascript - 添加到购物车逻辑
- python - 网页抓取过程
- javascript - 使用 moment.js 我如何将 day(0) 设置为本周的星期日而不是前一周
- python - ImportError: DLL load failed while importing _C: 没有足够的内存资源来处理这个命令
- sql-server - 用户 '.' 登录失败 尝试使用 Nestjs 连接到本地 SQL Server 数据库时出错