NSRect vs CGRect: y-axis inversion

試著忘記壹切 提交于 2021-01-27 02:46:10

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/17057757/nsrect-vs-cgrect-y-axis-inversion

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!