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?
Swift 4.2 use theRect.inset(by: theInsets)
.
Objective c use 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}}
Further useful functions for operating on CGRect
s are covered by this note.
Say you want the bounds,
but for example less two pixels on the bottom:
let ei = UIEdgeInsetsMake(0, 0, 2, 0) // top-left-bottom-right
let smaller = UIEdgeInsetsInsetRect(bounds, ei)
That's it.
Take two off the bottom:
let newBounds = UIEdgeInsetsInsetRect(bounds, UIEdgeInsetsMake(0, 0, 2, 0))
Cheers
I guess the new way looks better...
let newCGRect = oldCGRect.inset(by: UIEdgeInsets(top: 0, left: 8, bottom: 0, right: 8))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With