Don't Forget About CGGeometry Reference

Feb 8, 2012

If you find yourself doing something like the following, there’s a much easier way.

CGFloat xCenter = rect.origin.x + (rect.size.width / 2)

CGGeometry.h defines some incredibly handy macros (documented in CGGeometry Reference) that make easier.

For example, the above could simply be

CGFloat xCenter = CGRectGetMidX(rect);

A few more handy examples

// Determine if 2 rects intersect each other
if (CGRectIntersectsRect(rect1, rect2)) {
	// Collision
}

// Shrink a rect around its center, passing width and height deltas
CGRect smallerRect = CGRectInset(sourceRect, 50, 100);

// Grow a rect around its center, passing width and height deltas
CGRect smallerRect = CGRectInset(sourceRect, -50, -100);

// Create a new rect from the intersection of 2 rects
CGRect intersectionRect = CGRectIntersection(rect1, rect2);