Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSRect vs CGRect: y-axis inversion

So I'm trying to convert an NSRect to a CGRect. I used NSRectToCGRect() which copies everything over finely, but does not take into account y-origin axis.

The problem: A CGRect origin of (0,0) is the top left. NSRect origin (0,0) is bottom left.

Thus an NSRect (0,0,100,100) box is positioned at the bottom left of your screen, while a CGRect (0,0,100,100) box is placed at the top left of your screen.

I have a hack that fixes the y-origin through basic math:

fixedOriginY = screenHeight - NSRect.size.height - NSRect.origin.y

Thus the equivalent of an NSRect (0,0,100,100) is actually CGRect (0,800,100,100) (on my 900px height MBA). However I don't like this, I have a feeling it will break/have issues with retina or future complications.

Does anyone have a solution or idea on how to correctly convert NSRect to CGRect?

like image 320
user339946 Avatar asked Jun 12 '13 04:06

user339946


1 Answers

Whether the origin of a rectangle is at its top left or bottom left depends on the coordinate system in which you use the rectangle. It does not depend on whether you use CGRect or NSRect.

Typically, AppKit uses coordinate systems where the lower-left corner is the origin. Similarly, a CGContext that you create puts the origin at the lower left.

On the other hand, Quartz Event Services and Quartz Display Services put the origin at the upper left. UIKit (on iOS) puts the origin at the upper left. You can override isFlipped in an NSView subclass (on OS X) to put its origin at the upper left.

Your basic math is necessary and proper when you are converting a rectangle from a traditional (lower-left origin) to flipped (upper-left origin) coordinate system.

like image 170
rob mayoff Avatar answered Oct 21 '22 14:10

rob mayoff