I was wondering if there was any way to combine a CGRect with another CGRect to get a new CGRect. Does swift have any preset functionality to do this or is there another way of achieving this?
Asked
Active
Viewed 5,258 times
9
-
1Does this assume the rects are next to each other? What would be the algorithm/approach for "combining" two rectangles, in a general sense? – Craig Otis May 29 '15 at 15:55
-
@CraigOtis yes exactly, two CGRects next to each other for example. I'm wondering if its possible to combine the two. – Zouvv May 29 '15 at 15:56
-
@rmaddy CGRectUnion: "Returns the smallest rectangle that contains the two source rectangles." I don't think its the right one – Zouvv May 29 '15 at 16:00
-
1@Zouvv Clarify what you are actually looking for then because I think `CGRectUnion` is what you want. – rmaddy May 29 '15 at 16:04
-
@rmaddy I quite simply have two CGRects that appear next to each other, then I want to combine them into one CGRect. but I will try that anyway, thanks – Zouvv May 29 '15 at 16:17
2 Answers
18
let rect1 = CGRect(x: 0, y: 0, width: 100, height: 100)
let rect2 = CGRect(x: 40, y: 40, width: 150, height: 150)
let union = rect1.union(rect2) // {x 0 y 0 w 190 h 190}
See for more:

pkamb
- 33,281
- 23
- 160
- 191

Mikael Hellman
- 2,664
- 14
- 22
11
Swift 3 and newer:
let rect1 = CGRect(x: 0, y: 0, width: 100, height: 100)
let rect2 = CGRect(x: 40, y: 40, width: 150, height: 150)
let union = rect1.union(rect2) // {x 0 y 0 w 190 h 190}
Result is standardized, so resulting width and height are always positive:
let rect3 = CGRect(x: 0, y: 0, width: -100, height: -100)
let clone = rect3.union(rect3) // {x -100 y -100 w 100 h 100}
Documentation: https://developer.apple.com/documentation/coregraphics/cgrect/1455837-union

Cœur
- 37,241
- 25
- 195
- 267