Skip to content

Commit 9ec1314

Browse files
committed
added BoundingBox.intersection(:_) method and unit test.
1 parent 3894e1a commit 9ec1314

File tree

2 files changed

+29
-0
lines changed

2 files changed

+29
-0
lines changed

BezierKit/BezierKitTests/BoundingBoxTests.swift

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,4 +111,22 @@ class BoundingBoxTests: XCTestCase {
111111
XCTAssertEqual(result, BoundingBox(p1: CGPoint(x: 1.0, y: 1.0), p2: CGPoint(x: 3.0, y: 5.0)))
112112
}
113113

114+
func testIntersection() {
115+
let box1 = BoundingBox(p1: CGPoint(x:0,y:0), p2: CGPoint(x:3,y:2))
116+
let box2 = BoundingBox(p1: CGPoint(x:2,y:1), p2: CGPoint(x:4,y:5)) // overlaps box1
117+
let box3 = BoundingBox(p1: CGPoint(x:2,y:4), p2: CGPoint(x:4,y:5)) // does not overlap box1
118+
let box4 = BoundingBox(p1: CGPoint(x:3,y:0), p2: CGPoint(x:5,y:2)) // overlaps box1 exactly on x edge
119+
let box5 = BoundingBox(p1: CGPoint(x:0,y:2), p2: CGPoint(x:3,y:4)) // overlaps box1 exactly on y edge
120+
let box6 = BoundingBox(p1: CGPoint(x:0,y:0), p2: CGPoint(x:-5,y:-5)) // overlaps box1 only at (0,0)
121+
let expectedBox = BoundingBox(p1: CGPoint(x:2,y:1), p2: CGPoint(x:3,y:2))
122+
XCTAssertEqual(box1.intersection(box2), expectedBox)
123+
XCTAssertEqual(box2.intersection(box1), expectedBox)
124+
XCTAssertEqual(box1.intersection(box3), BoundingBox.empty)
125+
XCTAssertEqual(box1.intersection(BoundingBox.empty), BoundingBox.empty)
126+
XCTAssertEqual(BoundingBox.empty.intersection(box1), BoundingBox.empty)
127+
XCTAssertEqual(BoundingBox.empty.intersection(BoundingBox.empty), BoundingBox.empty)
128+
XCTAssertEqual(box1.intersection(box4), BoundingBox(p1: CGPoint(x:3,y:0), p2: CGPoint(x:3,y:2)))
129+
XCTAssertEqual(box1.intersection(box5), BoundingBox(p1: CGPoint(x:0,y:2), p2: CGPoint(x:3,y:2)))
130+
XCTAssertEqual(box1.intersection(box6), BoundingBox(p1: CGPoint.zero, p2: CGPoint.zero))
131+
}
114132
}

BezierKit/Library/Types.swift

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,17 @@ public struct BoundingBox: Equatable {
5454
self.max = CGPoint.max(self.max, other.max)
5555
return self
5656
}
57+
public func intersection(_ other: BoundingBox) -> BoundingBox {
58+
let box = BoundingBox(min: CGPoint.max(self.min, other.min),
59+
max: CGPoint.min(self.max, other.max))
60+
guard box.max.x - box.min.x >= 0, box.max.y - box.min.y >= 0 else {
61+
return BoundingBox.empty
62+
}
63+
return box
64+
}
65+
public var isEmpty: Bool {
66+
return self.min.x > self.max.x || self.min.y > self.max.y
67+
}
5768
public init(p1: CGPoint, p2: CGPoint) {
5869
self.min = CGPoint.min(p1, p2)
5970
self.max = CGPoint.max(p1, p2)

0 commit comments

Comments
 (0)