是否有检测线是否接触矩形的功能

Is there a function to detect if a line touches a rect

我们可以检测一个点是否在一个矩形中 CGRectContainsPoint.

有没有一种简单的方法来检测一条线是否接触到一个矩形?

感谢 Rob:original post for part one

extension CGPoint {

    static func intersectionBetweenSegments(p0: CGPoint, _ p1: CGPoint, _ p2: CGPoint, _ p3: CGPoint) -> CGPoint? {
        var denominator = (p3.y - p2.y) * (p1.x - p0.x) - (p3.x - p2.x) * (p1.y - p0.y)
        var ua = (p3.x - p2.x) * (p0.y - p2.y) - (p3.y - p2.y) * (p0.x - p2.x)
        var ub = (p1.x - p0.x) * (p0.y - p2.y) - (p1.y - p0.y) * (p0.x - p2.x)
        if (denominator < 0) {
            ua = -ua; ub = -ub; denominator = -denominator
        }

        if ua >= 0.0 && ua <= denominator && ub >= 0.0 && ub <= denominator && denominator != 0 {
            return CGPoint(x: p0.x + ua / denominator * (p1.x - p0.x), y: p0.y + ua / denominator * (p1.y - p0.y))
        }

        return nil
    }

}

将上面的函数应用到CGRect的所有边:

extension CGRect {

    func intersectionsWithLine(p0:CGPoint, _ p1: CGPoint) -> [CGPoint] {

        let a = (self.origin,CGPoint(x: self.width, y: self.origin.y))
        let b = (a.1,CGPoint(x: a.1.x, y: self.height))
        let c = (b.1,CGPoint(x: a.0.x, y: b.1.y))
        let d = (c.1,a.0)

        let lines = [a,b,c,d]

        var intersections : [CGPoint] = []

        for line in lines {
            if let point = CGPoint.intersectionBetweenSegments(p0, p1, line.0, line.1) {
                intersections.append(point)
            }
        }

        return intersections
    }
}

如果结果为空数组,则没有交集。