views:

445

answers:

2

Is there any difference between a CGRect and an NSRect? In particular, I'm wondering about the position of the origin. Are there any important differences I need to know about?

+8  A: 

They're the same. This link has more information. Copied here for quick reference:

CGRect is the CoreGraphics equivalent of NSRect.

They are deliberately made to have the same layout in memory. As such, it is allowed to convert an NSRect to a CGRect by doing this:

CGRect cgrect = *(CGRect *)&nsrect;

CoreGraphics also provides a CGRectMake() function which works the same as NSMakeRect() (note the reversal of verb and object in the names) except it returns a CGRect.

Carl Norum
Well, that's allowed except that it breaks strict aliasing rules in the compiler. I'll fix that wiki page. Use NSRectFromCGRect and NSRectToCGRect to convert.
Ken
In 64-bit, or when you compile with `NS_BUILD_32_LIKE_64`, `NSRect` is defined as `CGRect`, so you don't even need to jump through the pointer hoop.
Peter Hosey
A: 

In particular, I'm wondering about the position of the origin.

That depends on where you got the rect and where you're using it. In general, Core Graphics and UIKit use flipped co-ordinates (origin upper-left, positive y going down), whereas AppKit uses unflipped co-ordinates (origin lower-left, positive y going up). But it is possible to flip or unflip co-ordinates from each API, and some classes, such as NSImage and NSView, make it very easy to do so.

Peter Hosey