【问题标题】:Can I adjust a CGRect with a UIEdgeInsets?我可以用 UIEdgeInsets 调整 CGRect 吗?
【发布时间】:2015-01-02 11:44:30
【问题描述】:

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

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

我应该自己编码吗?

【问题讨论】:

    标签: cgrect uiedgeinsets


    【解决方案1】:

    TL;DR

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

    目标c使用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}}
    

    说明

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

    告诉我更多

    this note 涵盖了在 CGRects 上操作的更多有用功能。

    【讨论】:

    • 太棒了!我应该预料到这种方法存在,但我很感激我不必努力寻找它! ;-)
    【解决方案2】:

    2018 ... Swift4

    说你想要边界,

    但例如在底部上少于两个像素:

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

    就是这样。

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

    从底部取下两个:

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

    干杯

    【讨论】:

    • 不寻常的是 Swift 3 没有在 CGRect:rect.insetBy(edgeInset) 或类似的东西上包含这个函数。
    • 不,我的意思是语法。它不是一个冗长的函数,它可以直接对CGRect 进行操作。
    • 我知道。但它可能是。就像所有其他 CGRect 函数一样。
    • 实际上 - 你说得对,卢卡斯。比如.union就是一个很好的例子。
    【解决方案3】:

    仍然是 2018 ... Swift 4.2

    我猜新方法看起来更好......

    let newCGRect = oldCGRect.inset(by: UIEdgeInsets(top: 0, left: 8, bottom: 0, right: 8))
    

    【讨论】:

      【解决方案4】:
      CGRect insetRect = CGRectInset(rOriginalRect, fInsetX, fInsetY);
      

      【讨论】:

      • 在 Stack Overflow 上不鼓励仅使用代码的答案,因为它们没有解释它如何解决问题。请编辑您的答案以解释此代码的作用以及它如何回答问题,以便它对 OP 以及其他有类似问题的用户有用。
      猜你喜欢
      • 2013-10-12
      • 1970-01-01
      • 2015-01-19
      • 1970-01-01
      • 2021-07-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多