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:

1

2

3

4

5

CGRectrect1=CGRectMake(100,100,100,100);

CGRectrect2=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:

1

2

3

4

5

6

7

8

9

10

CGRectrect3=CGRectMake(100,100,100,100);

CGRectrect4=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:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

CGRectrect5=CGRectMake(100,100,100,100);

// Use positive values for a smaller rectangle

CGRectrect6=CGRectInset(rect,25,25);

NSLog(@"%rect5: %@",NSStringFromCGRect(rect5));

NSLog(@"%rect6: %@",NSStringFromCGRect(rect6));

...

CGRectrect7=CGRectMake(100,100,100,100);

// Use negative values for a larger rectangle

CGRectrect8=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:

1

2

3

NSString*str=@"{{0,0},{50,50}}";

CGRectrect9=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: