How to combine CGRects with each other in Swift
Asked Answered
A

3

9

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?

Assault answered 29/5, 2015 at 15:54 Comment(5)
Does this assume the rects are next to each other? What would be the algorithm/approach for "combining" two rectangles, in a general sense?Degrading
@CraigOtis yes exactly, two CGRects next to each other for example. I'm wondering if its possible to combine the two.Assault
@rmaddy CGRectUnion: "Returns the smallest rectangle that contains the two source rectangles." I don't think its the right oneAssault
@Assault Clarify what you are actually looking for then because I think CGRectUnion is what you want.Gardiner
@Gardiner 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, thanksAssault
B
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:

Benares answered 29/5, 2015 at 16:2 Comment(0)
P
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

Pogonia answered 30/6, 2017 at 16:44 Comment(0)
T
0

Just for the record ...

Here's the by-hand code to "increase a rect, moving outwards any of the four edges necessary, so as to engulf another rect".

extension CGRect {
    
    ///The result is increased in size enough to encompass the supplied extra rect.
    func engulf(_ r: CGRect) -> CGRect {
        return self.inset(by: UIEdgeInsets(
            top: r.minY < minY ? -(minY - r.minY) : 0,
            left: r.minX < minX ? -(minX - r.minX) : 0,
            bottom: r.maxY > maxY ? -(r.maxY - maxY) : 0,
            right: r.maxX > maxX ? -(r.maxX - maxX) : 0
        ))
    }
}

Nowadays with Apple's fabulous functions like union and divided#atDistance#from you rarely need to write these yourself.

I find a base like this can be handy if you are doing the inevitable slight customizations you need.

(For example, you might need .. "Just like Apple's 'union' but never extend on the left", just to make a random example.)

Thorr answered 14/5 at 19:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.