Skip to content

Commit

Permalink
added BoundingBox.intersection(:_) method and unit test.
Browse files Browse the repository at this point in the history
  • Loading branch information
hfutrell committed Jan 31, 2019
1 parent 3894e1a commit 9ec1314
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
18 changes: 18 additions & 0 deletions BezierKit/BezierKitTests/BoundingBoxTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -111,4 +111,22 @@ class BoundingBoxTests: XCTestCase {
XCTAssertEqual(result, BoundingBox(p1: CGPoint(x: 1.0, y: 1.0), p2: CGPoint(x: 3.0, y: 5.0)))
}

func testIntersection() {
let box1 = BoundingBox(p1: CGPoint(x:0,y:0), p2: CGPoint(x:3,y:2))
let box2 = BoundingBox(p1: CGPoint(x:2,y:1), p2: CGPoint(x:4,y:5)) // overlaps box1
let box3 = BoundingBox(p1: CGPoint(x:2,y:4), p2: CGPoint(x:4,y:5)) // does not overlap box1
let box4 = BoundingBox(p1: CGPoint(x:3,y:0), p2: CGPoint(x:5,y:2)) // overlaps box1 exactly on x edge
let box5 = BoundingBox(p1: CGPoint(x:0,y:2), p2: CGPoint(x:3,y:4)) // overlaps box1 exactly on y edge
let box6 = BoundingBox(p1: CGPoint(x:0,y:0), p2: CGPoint(x:-5,y:-5)) // overlaps box1 only at (0,0)
let expectedBox = BoundingBox(p1: CGPoint(x:2,y:1), p2: CGPoint(x:3,y:2))
XCTAssertEqual(box1.intersection(box2), expectedBox)
XCTAssertEqual(box2.intersection(box1), expectedBox)
XCTAssertEqual(box1.intersection(box3), BoundingBox.empty)
XCTAssertEqual(box1.intersection(BoundingBox.empty), BoundingBox.empty)
XCTAssertEqual(BoundingBox.empty.intersection(box1), BoundingBox.empty)
XCTAssertEqual(BoundingBox.empty.intersection(BoundingBox.empty), BoundingBox.empty)
XCTAssertEqual(box1.intersection(box4), BoundingBox(p1: CGPoint(x:3,y:0), p2: CGPoint(x:3,y:2)))
XCTAssertEqual(box1.intersection(box5), BoundingBox(p1: CGPoint(x:0,y:2), p2: CGPoint(x:3,y:2)))
XCTAssertEqual(box1.intersection(box6), BoundingBox(p1: CGPoint.zero, p2: CGPoint.zero))
}
}
11 changes: 11 additions & 0 deletions BezierKit/Library/Types.swift
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,17 @@ public struct BoundingBox: Equatable {
self.max = CGPoint.max(self.max, other.max)
return self
}
public func intersection(_ other: BoundingBox) -> BoundingBox {
let box = BoundingBox(min: CGPoint.max(self.min, other.min),
max: CGPoint.min(self.max, other.max))
guard box.max.x - box.min.x >= 0, box.max.y - box.min.y >= 0 else {
return BoundingBox.empty
}
return box
}
public var isEmpty: Bool {
return self.min.x > self.max.x || self.min.y > self.max.y
}
public init(p1: CGPoint, p2: CGPoint) {
self.min = CGPoint.min(p1, p2)
self.max = CGPoint.max(p1, p2)
Expand Down

0 comments on commit 9ec1314

Please sign in to comment.