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

标签 ios swift core-graphics cgrect

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

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

最佳答案

感谢罗布: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
    }
}

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

关于ios - 是否有检测线是否接触矩形的功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34615475/

相关文章:

ios - cocoa pod : No such file or directory

ios - CouchDB Kitura 执行 View

image-processing - 将极坐标应用于 UIImage

objective-c - 如何访问 NSBitmapImageRep 的像素?

ios - iPad - 解析一个非常大的 json - 文件(50 到 100 mb 之间)

ios - 我可以使用 iOS 应用程序在页面的墙上发帖吗?

ios - 显示Section时如何自定义动画?

iOS:CGImageCreateWith[PNG 或 JPEG]DataProvider 导致段错误

ios - 使用 for 循环时发生奇怪的崩溃

ios - 如何更换来电时的默认提醒?