如何在 Swift 中将 CGRect 相互组合

问题描述 投票:0回答:3

我想知道是否有任何方法可以将一个 CGRect 与另一个 CGRect 组合起来以获得一个新的 CGRect。 swift 是否有任何预设功能来执行此操作,或者是否有其他方法可以实现此目的?

ios swift cgrect
3个回答
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}

查看更多:


11
投票

Swift 3 及更新版本:

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}

结果是标准化的,因此所得的宽度和高度始终为正值:

let rect3 = CGRect(x: 0, y: 0, width: -100, height: -100)
let clone = rect3.union(rect3) // {x -100 y -100 w 100 h 100}

文档: https://developer.apple.com/documentation/coregraphics/cgrect/1455837-union


0
投票

仅供记录...

这是“增加一个矩形,向外移动必要的四个边中的任何一个,以便吞没另一个矩形”的手动代码。

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

如今,有了 Apple 的出色功能,例如

union
divided#atDistance#from
,您很少需要自己编写这些功能。

我发现,如果您正在进行不可避免的轻微定制,这样的底座会很方便。

(例如,您可能需要..“就像Apple的'union'但永远不会向左延伸”,只是为了做一个随机的例子。)

© www.soinside.com 2019 - 2024. All rights reserved.