Can I adjust a CGRect with a UIEdgeInsets?

Benjohn picture Benjohn · Jan 2, 2015 · Viewed 18.5k times · Source

I've got a CGRect, and I'd like to adjust it with a UIEdgeInsets.

It seems like perhaps there might be a built in function that does this. I've looked for a CGRectAdjustByInsets or functions with some other CGRect… prefix, but I didn't find anything.

Should I code my own?

Answer

Benjohn picture Benjohn · Jan 2, 2015

TL;DR

Swift 4.2 use theRect.inset(by: theInsets).

Objective c use 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

  • A positive inset moves the rectangle's edge inwards (towards the rectangle middle).
  • A negative inset moves the edge outward (away from the rectangle middle).
  • A zero inset will leaves the edge alone.

Tell Me More

Further useful functions for operating on CGRects are covered by this note.