How to combine CGRects with each other in Swift

Deadly 提交于 2019-12-23 10:15:36

问题


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?


回答1:


let rect1 = CGRect(x: 0, y: 0, width: 100, height: 100)
let rect2 = CGRect(x: 40, y: 40, width: 150, height: 150)
CGRectUnion(rect1, rect2) // {x 0 y 0 w 190 h 190}

See for more:

  • https://developer.apple.com/documentation/coregraphics/cggeometry
  • https://developer.apple.com/documentation/coregraphics/cgrect
  • https://developer.apple.com/documentation/coregraphics/cgrect/1455837-union



回答2:


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



来源:https://stackoverflow.com/questions/30533937/how-to-combine-cgrects-with-each-other-in-swift

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!