Skip to content

Commit d9c77c1

Browse files
committed
Rect: refine Rect.applying(_:)
Use a bit more functional style computation in the application of a transformation. Use a single pass to simultaneously compute the new bounds of the rectangle.
1 parent 256eaed commit d9c77c1

File tree

1 file changed

+14
-10
lines changed

1 file changed

+14
-10
lines changed

Sources/SwiftWin32/CG/Rect.swift

Lines changed: 14 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -92,19 +92,23 @@ public struct Rect {
9292

9393
/// Applies an affine transform to a rectangle.
9494
public func applying(_ transform: AffineTransform) -> Rect {
95+
if transform.isIdentity { return self }
96+
9597
let points: [Point] = [
96-
self.origin,
97-
self.origin + Point(x: self.size.width, y: 0),
98-
self.origin + Point(x: 0, y: self.size.height),
99-
self.origin + Point(x: self.size.width, y: self.size.height),
98+
Point(x: minX, y: minY), // top left
99+
Point(x: maxX, y: minY), // top right
100+
Point(x: minX, y: maxY), // bottom left
101+
Point(x: maxX, y: maxY), // bottom right
100102
].map { $0.applying(transform) }
101103

102-
let xs: [Double] = points.map { $0.x }
103-
let ys: [Double] = points.map { $0.y }
104-
105-
return Rect(origin: Point(x: xs.min()!, y: ys.min()!),
106-
size: Size( width: xs.max()! - xs.min()!,
107-
height: ys.max()! - ys.min()!))
104+
let (minX, minY, maxX, maxY): (Double, Double, Double, Double) =
105+
points.map { ($0.x, $0.y) }
106+
.reduce((.infinity, .infinity, -.infinity, -.infinity), {
107+
(min($0.0, $1.0), min($0.1, $1.1), max($0.2, $1.0), max($0.3, $1.1))
108+
})
109+
110+
return Rect(origin: Point(x: minX, y: minY),
111+
size: Size(width: maxX - minX, height: maxY - minY))
108112
}
109113

110114
/// Returns a rectangle with an origin that is offset from that of the source

0 commit comments

Comments
 (0)