With an understanding ofC structures, and thedefinitions of CGRect, CGSize and CGPointbehind us, let’s look at a handful of functions for working with these structures.
CGRectMake and NSStringFromCGRect
With CGRectMake we can create a new CGRect structure. The rectangles below have differing starting points, however, each have a width and height of 100. The function NSStringFromCGRect returns a string object that defines the rectangle passed in as a parameter:
CGRect rect1 = CGRectMake(100, 100, 100, 100); CGRect rect2 = CGRectMake(190, 190, 100, 100); NSLog(@"rect1: %@", NSStringFromCGRect(rect1)); NSLog(@"rect2: %@", NSStringFromCGRect(rect2));
Note: The output of all examples are shown in the image at the bottom of this post.
CGRectIntersect
To determine if two rectangles intersect, you can write code as follows:
CGRect rect3 = CGRectMake(100, 100, 100, 100); CGRect rect4 = CGRectMake(190, 190, 100, 100); if (CGRectIntersectsRect(rect3, rect4) == 1) NSLog(@"The rectangles intersect"); else NSLog(@"The rectangles do not intersect"); NSLog(@"rect3: %@", NSStringFromCGRect(rect3)); NSLog(@"rect4: %@", NSStringFromCGRect(rect4));
CGRectInset
If you need to create a rectangle that is either larger or smaller than an existing rectangle, centered on the same point, try CGRectInset:
CGRect rect5 = CGRectMake(100, 100, 100, 100); // Use positive values for a smaller rectangle CGRect rect6 = CGRectInset(rect, 25, 25); NSLog(@"%rect5: %@", NSStringFromCGRect(rect5)); NSLog(@"%rect6: %@", NSStringFromCGRect(rect6)); ... CGRect rect7 = CGRectMake(100, 100, 100, 100); // Use negative values for a larger rectangle CGRect rect8 = CGRectInset(rect, -25, -25); NSLog(@"rect7: %@", NSStringFromCGRect(rect7)); NSLog(@"rect8: %@", NSStringFromCGRect(rect8));
CGRectFromString
A little more uncommon, is creating rectangles from a string, however, if the need arises:
NSString *str = @"{{0,0},{50,50}}"; CGRect rect9 = CGRectFromString(str); NSLog(@"rect9: %@", NSStringFromCGRect(rect9));
Functions for CGSize and CGPoint
As you would expect, there are similar functions to those above for working with CGSize and CGPoint:
- CGSizeMake
- CGSizeEqualToSize
- CGPointMake
- CGPointEqualToPoint
http://iphonedevelopertips.com/c/cgrect-cgsize-and-cgpoint-functions.html