我可以使用UIEdgeInsets调整CGRect吗?

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

我有一个CGRect,我想用UIEdgeInsets调整它。

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

我应该自己编码吗?

cgrect uiedgeinsets
3个回答
88
投票

TL;DR

Swift 4.2使用theRect.inset(by: theInsets)

目标c使用UIEdgeInsetsInsetRect(theRect, theInsets)

Example

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

Explanation

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

Tell Me More

CGRect涵盖了在this notes上运行的更多有用功能。


8
投票

2018 ... Swift4

说你想要的界限,

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

let ei = UIEdgeInsetsMake(0, 0, 2, 0)   // top-left-bottom-right
let smaller = UIEdgeInsetsInsetRect(bounds, ei)

而已。

If you prefer to write it as one line, it's just

从底部取下两个:

let newBounds = UIEdgeInsetsInsetRect(bounds, UIEdgeInsetsMake(0, 0, 2, 0))

干杯


6
投票

Still 2018 ... Swift 4.2

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

let newCGRect = oldCGRect.inset(by: UIEdgeInsets(top: 0, left: 8, bottom: 0, right: 8))
© www.soinside.com 2019 - 2024. All rights reserved.