CGRect, CGSize and CGPoint

Wed, Nov 5

Digging into development of iPhone applications, you’ll eventually encounter references to CGRect, CGSize, and CGPoint. These references are to C structures (see this post for more information on structures). This post will provide a high-level view of what comprises CGRect and its counterparts. Here is how CGRect is defined:

1
2
3
4
5
struct CGRect {
   CGPoint origin;
   CGSize size;
};
typedef struct CGRect CGRect;

Going a little further, we can find that CGPoint and CGSize are defined as follows:

1
2
3
4
5
6
7
8
9
10
11
struct CGPoint {
   CGFloat x;
   CGFloat y;
};
typedef struct CGPoint CGPoint;
 
struct CGSize {
   CGFloat width;
   CGFloat height;
};
typedef struct CGSize CGSize;

And to wrap up, CGFloat looks as follows:

1
2
typedef float CGFloat;    // 32-bit
typedef double CGFloat; // 64-bit

Here’s what we can summarize, a CGRect defines a rectangle as an origin (x and y location) and its size (width and height), with all values represented as floats. Access to the member variables of these structures (and all structure members for that matter) is through dot syntax as shown in the example below:

1
2
3
4
5
6
7
  CGRect bounds = [[UIScreen mainScreen] bounds];
  CGRect appframe= [[UIScreen mainScreen] applicationFrame];
 
  NSLog(@"mainScreen bounds: %.0f, %.0f, %3.0f, %3.0f", 
     bounds.origin.x, bounds.origin.y, bounds.size.width, bounds.size.height);
  NSLog(@"mainScreen applicationFrame: %.0f, %.0f, %3.0f, %3.0f", 
     appframe.origin.x, appframe.origin.y, appframe.size.width, appframe.size.height);

In an upcoming post I’ll look into some of the functions that are available to us when working with the above structures.

9 comments

Nice reference.

You are printing origin.x twice rather then origin.x & origin.y :)

by Jarryd on Apr 1, 2011. #

Thanks Jarryd, I’ve updated the example.

by John Muchow on Apr 4, 2011. #

Clear. Simple. Good Example.

by Richard on May 30, 2011. #

Really Helpful for first time started programmer

by Moniruzzaman_cse on Jun 16, 2011. #

Thanks, for the info! :)

by tooYoungNotHappy on Aug 3, 2011. #

Thanks…:)

by Vishnu Menon on Sep 24, 2011. #

we can use NSStringToCGRect… like functions to print everything in one shot NSLog(@”%@”, NSStringTo..(rect));

Nice article though! thanks

by Guru on Apr 12, 2012. #

Very useful

by Abdiel Soto on Aug 21, 2012. #

thanks for this Article :)
it`s really clear

by feeliwood on Sep 17, 2012. #