Mac OS X Cocoa, Flipping Y Coordinate in Global Screen Coordinate Space

浪尽此生 提交于 2021-01-27 22:20:47

问题


How do I flip the y value of an NSPoint to a flipped coordinate space.

I have two sources of points, both in global screen space, but one is flipped:

  1. one from a screen coordinate space with 0,0 = top left.

  2. one from a screen coordinate space with 0,0 = bottom left.

I need to flip the second one (bottom left) to be in the same space as the first one, top left. How can I do that on an NSPoint or CGPoint?


回答1:


For Mac OSX Cocoa, you can flip the y Coordinate for a view, just override isFlipped to return YES for each view:

- (BOOL)isFlipped {
    return YES;
}



回答2:


If you have multiple monitors, the overall height of the global coordinate space may be larger than the vertical height on any individual display. I found it necessary to use the following code (given originalPoint) to find that:

let globalHeight = screens.map {$0.frame.origin.y + $0.frame.height}.max()!
let flippedY = globalHeight - originalPoint.y
let convertedPoint = NSPoint(x: originalPoint.x, y: flippedY)



回答3:


Let's say you have a point in a bottom left coordinate space, called 'originalPoint'. To flip this point to a top left coordinate space, you can use the following code:

let screenFrame = (NSScreen.main()?.frame)!
let flippedY = screenFrame.size.height - originalPoint.y
let convertedPoint = NSPoint(x: originalPoint.x, y: flippedY)

We can also make an extension:

extension NSPoint {

    var flipped: NSPoint {

        let screenFrame = (NSScreen.main()?.frame)!
        let screenY = screenFrame.size.height - self.y
        return NSPoint(x: self.x, y: screenY)  
    }
}

Use:

let flippedPoint = originalPoint.flipped


来源:https://stackoverflow.com/questions/6901651/mac-os-x-cocoa-flipping-y-coordinate-in-global-screen-coordinate-space

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