Functions for CGRect

In the cocoa (cocoa touch) framework, CGRect structure are used in many places because its rendering system depends on Core Graphics library. Here are the useful functions for CGRect structure.

Function Description
CGRectMake() Creates CGRect structure from integer values

// creates CGRect with  x=0, y=0, width=100, height=100
CGRect rect = CGRectMake(0, 0, 100, 100);
CGRectFromString() Creates CGRect structure from string

// creates CGRect with x=10, y=20, width=100, height=200
CGRect rect = CGRectFromString(@"{{10, 20}, {100, 200}}");
NSStringFromCGRect() Creates NSString object for specified CGRect structure. It is same format as the argument for CGRectFromString().

CGRect rect = CGRectMake(0, 0, 100, 100);

// outputs {{0, 0}, {100, 100}}
NSLog(@"%@", NSStringFromCGRect(rect));
CGRectEqualToRect() Checks whether given two CGRect are equal in both size and position.

CGRect rect1 = CGRectMake(0, 0, 100, 100);
CGRect rect2 = CGRectMake(10, 20, 100, 100);

// returns false
CGRectEqualToRect(rect1, rect2);
CGRectIntersection() Returns the intersection of two rectangles. Note that if two rectangles do not intersect, it returns the null rectangle.

CGRect rect1 = CGRectMake(0, 0, 100, 100);
CGRect rect2 = CGRectMake(10, 20, 100, 100);
CGRect intersect = CGRectIntersection(rect1, rect2);

// returns {{10, 20},{90, 80}}
NSLog(@"%@", NSStringFromCGRect(intersect));
CGRectIsNull() Checks null

CGRect rect1 = CGRectMake(0, 0, 100, 100);
CGRect rect2 = CGRectMake(200, 200, 100, 100);
CGRect intersect = CGRectIntersection(rect1, rect2);

// returns YES (1)
NSLog(@"%d", CGRectIsNull(intersect));

There are more functions for this purpose. Check Appleā€™s website for the detail.

,

No comments yet.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.