CGRect, CGSize and CGPoint

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.

  1. Nice reference.

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

  2. Really Helpful for first time started programmer

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

    Nice article though! thanks

Comments are closed.