我们可以检测一个点是否在一个矩形中 CGRectContainsPoint。
有没有一种简单的方法来检测线是否正在接触一个矩形?
答案 0 :(得分:1)
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
}
}
如果结果是空数组,则没有交叉点。