Reputation: 11645
We can detect if a point is in a rect with CGRectContainsPoint.
Is there a simple way to detect if a line is touching a rect?
Upvotes: 1
Views: 85
Reputation: 8391
Credits to 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
}
}
Apply the function above to all sides of a 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
}
}
If the result is an empty array, there are no intersections.
Upvotes: 1