首页 > 解决方案 > 计算打开 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
        }

    }

标签: swiftcoordinatestrigonometryuibezierpath

解决方案


推荐阅读