我可以使用UIEdgeInsets调整CGRect吗?

Ben*_*ohn 42 cgrect uiedgeinsets

我有一个CGRect,我想调整它UIEdgeInsets.

似乎可能有一个内置函数可以做到这一点.我已经找了一个CGRectAdjustByInsets或带有其他CGRect…前缀的函数,但我没有找到任何东西.

我应该自己编码吗?

Ben*_*ohn 91

TL; DR

使用该功能 theRect.inset(by: theInsets)

对于Swift 4.2使用UIEdgeInsetsInsetRect(theRect, theInsets).

// CGRectMake takes: left, bottom, width, height.
const CGRect originalRect = CGRectMake(0, 0, 100, 50);

// UIEdgeInsetsMake takes: top, left, bottom, right.
const UIEdgeInsets insets = UIEdgeInsetsMake(10, 10, -20, -20);

// Apply the insets…
const CGRect adjustedRect = UIEdgeInsetsInsetRect(originalRect, insets);

// What's the result?
NSLog(@"%@ inset by %@ is %@", 
      NSStringFromCGRect(originalRect),
      NSStringFromUIEdgeInsets(insets),
      NSStringFromCGRect(adjustedRect));

// Logs out…
// {{0, 0}, {100, 50}} inset by {10, 10, -20, -20} is {{10, 10}, {110, 60}}
Run Code Online (Sandbox Code Playgroud)

说明

  • 正插图将矩形的边缘向内移动(朝向矩形中间).
  • 负插入将边缘向外移动(远离矩形中间).
  • 零插入将使边缘独立.

告诉我更多

本说明CGRect涵盖了在s上操作的其他有用功能.


Fat*_*tie 8

2018年...... Swift4

说你想要的界限,

但是例如底部少了两个像素:

let ei = UIEdgeInsetsMake(0, 0, 2, 0)   // top-left-bottom-right
let smaller = UIEdgeInsetsInsetRect(bounds, ei)
Run Code Online (Sandbox Code Playgroud)

而已.

如果你更喜欢把它写成一行,那就是

从底部取下两个:

let newBounds = UIEdgeInsetsInsetRect(bounds, UIEdgeInsetsMake(0, 0, 2, 0))
Run Code Online (Sandbox Code Playgroud)

干杯

  • 不常见的是,Swift 3并没有将它作为函数包含在`CGRect`中:`rect.insetBy(edgeInset)`或类似的东西. (2认同)

bea*_*a13 7

2018年......斯威夫特4.2

我想新的方式看起来更好......

let newCGRect = oldCGRect.inset(by: UIEdgeInsets(top: 0, left: 8, bottom: 0, right: 8))
Run Code Online (Sandbox Code Playgroud)