从CGPoint到段的最短距离

时间:2015-02-13 17:33:30

标签: swift line cgpoint

我一直试图在我的代码中实现Douglas-Peucker algorithm,并且我能够将伪代码转换为Swift,除了shortestDistanceToSegment函数。我只能找到可以找到的Swift版本here,但我不明白它实际上是做什么的。

我需要一个函数,它将三个点作为参数(点和线的两端)并返回CGPoint和线段之间的最短距离。关于代码做什么(以及为什么)做的一些解释很好但不是必要的。

1 个答案:

答案 0 :(得分:9)

来自https://stackoverflow.com/a/27737081/535275的答案w /变量重命名&一些评论补充道:

/* Distance from a point (p1) to line l1 l2 */
func distanceFromPoint(p: CGPoint, toLineSegment v: CGPoint, and w: CGPoint) -> CGFloat {
    let pv_dx = p.x - v.x
    let pv_dy = p.y - v.y
    let wv_dx = w.x - v.x
    let wv_dy = w.y - v.y

    let dot = pv_dx * wv_dx + pv_dy * wv_dy
    let len_sq = wv_dx * wv_dx + wv_dy * wv_dy
    let param = dot / len_sq

    var int_x, int_y: CGFloat /* intersection of normal to vw that goes through p */

    if param < 0 || (v.x == w.x && v.y == w.y) {
        int_x = v.x
        int_y = v.y
    } else if param > 1 {
        int_x = w.x
        int_y = w.y
    } else {
        int_x = v.x + param * wv_dx
        int_y = v.y + param * wv_dy
    }

    /* Components of normal */
    let dx = p.x - int_x
    let dy = p.y - int_y

    return sqrt(dx * dx + dy * dy)
}