Zouvv
Zouvv

Reputation: 143

How to combine CGRects with each other in Swift

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?

Upvotes: 9

Views: 5653

Answers (3)

Fattie
Fattie

Reputation: 12592

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.)

Upvotes: 0

Mikael Hellman
Mikael Hellman

Reputation: 2724

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:

Upvotes: 18

Cœur
Cœur

Reputation: 38667

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

Upvotes: 11

Related Questions