Thursday, July 14, 2011

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:

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:

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:

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:

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);

No comments:

Post a Comment