Thursday, August 4, 2011

UIEdgeInsets.

Shrinking, Expanding, Edge Insetting
If you need to shrink a CGRect by a certain value horizontally and vertically you could do so by modifying the structure members themselves. But way more elegant is to use the provided convenient macro CGRectInset. Positive values will decrease the size evenly for the new rectangle to be centered in the old one. Negative values by the same token will increase it.
CGRect aRectangle = CGRectMake(0,0, 100, 200);
CGRect smallerRectangle = CGRectInset(aRectangle, 10, 20);
// result origin (10, 20) and size (80, 160)
This method is fine for 80% of use cases, but sometimes you want to apply different insets for each edge. Imagine, if you will that you want, to have a property contentInsets that would specify the distance a view content should have from each border. The structure of choice for this is UIEdgeInsets(top, left, bottom, right), and of course, there is also a matching Make macro available.
Once you have both you can easily apply the insets to your rect to receive the finally content rectangle. The macro for this purpose is UIEdgeInsetsInsetRect, would you have guessed?
CGRect rect = CGRectMake(0, 0, 100, 200);
UIEdgeInsets contentInsets = UIEdgeInsetsMake(10, 20, 30, 40);

CGRect result = UIEdgeInsetsInsetRect(rect, contentInsets);
NSLog(@"x: %f, y: %f, width: %f, height: %f",
result.origin.x, result.origin.y,
result.size.width, result.size.height);
// x: 20.000000, y: 10.000000, width: 40.000000, height: 160.000000
Actually the above NSLog is how I have been inspecting CGRect for the past 2 years. Right after I published the first version of this blog post I was pointed out to me that there is an even more elegant method: NSStringFromCGRect. Wow, a third as much key strokes.
NSLog(@"%@", NSStringFromCGRect(result));
// {{20, 10}, {40, 160}}
Wway more elegant, I’m sure you’ll agree? (Thanks Matt and Thomas But that’s the point of making these write ups. You learn a bit from writing them and you learn a bit more when other pros tell you the mistakes you made.

from: http://www.cocoanetics.com/2010/07/cgrect-tricks/

No comments:

Post a Comment