Skip to content

Commit 1c16a2a

Browse files
committed
Little bit of rect helper
1 parent c7d76ff commit 1c16a2a

2 files changed

Lines changed: 55 additions & 0 deletions

File tree

Sources/BaseKit/Geometry/Rect.swift

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,36 @@ public struct Rect: Hashable, Codable, Sendable {
5151
origin.isClose(to: other.origin, threshold: threshold)
5252
&& size.isClose(to: other.size, threshold: threshold)
5353
}
54+
55+
public func insetBy(dx: Real, dy: Real) -> Rect {
56+
Rect(
57+
x: minX + dx,
58+
y: minY + dy,
59+
width: width - 2.0 * dx,
60+
height: height - 2.0 * dy
61+
)
62+
}
63+
64+
public func offsetBy(dx: Real, dy: Real) -> Rect {
65+
Rect(
66+
x: minX + dx,
67+
y: minY + dy,
68+
width: width,
69+
height: height
70+
)
71+
}
72+
73+
public func center(inside biggerRect: Rect) -> Rect {
74+
let dx = (biggerRect.width - width) / 2.0
75+
let dy = (biggerRect.height - height) / 2.0
76+
return offsetBy(dx: dx, dy: dy)
77+
}
78+
79+
public func center(on insideRect: Rect) -> Rect {
80+
let dx = (width - insideRect.width) / 2.0
81+
let dy = (height - insideRect.height) / 2.0
82+
return offsetBy(dx: -dx, dy: -dy)
83+
}
5484
}
5585

5686
public extension Optional where Wrapped == Rect {
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
import BaseKit
2+
import Testing
3+
4+
5+
struct RectTests {
6+
@Test
7+
func testInset() {
8+
let subject = Rect(x: 25, y: 60, width: 100, height: 70)
9+
#expect(subject.insetBy(dx: 25, dy: 10) == Rect(x: 50, y: 70, width: 50, height: 50))
10+
}
11+
12+
@Test
13+
func testCenterInside() {
14+
let containingRect = Rect(x: 25, y: 50, width: 100, height: 50)
15+
let subject = Rect(x: 25, y: 50, width: 50, height: 50)
16+
#expect(subject.center(inside: containingRect) == Rect(x: 50, y: 50, width: 50, height: 50))
17+
}
18+
19+
@Test
20+
func testCenterOn() {
21+
let containedRect = Rect(x: 25, y: 50, width: 50, height: 50)
22+
let subject = Rect(x: 25, y: 50, width: 100, height: 50)
23+
#expect(subject.center(on: containedRect) == Rect(x: 0, y: 50, width: 100, height: 50))
24+
}
25+
}

0 commit comments

Comments
 (0)