Swift中如何将CGDisplayBounds()坐标转换为NSEvent.mouseLocation全局坐标
macOS Swift:将CGDisplayBounds坐标转换为与NSEvent.mouseLocation一致的坐标
首先明确两个坐标系的核心差异:
NSEvent.mouseLocation的坐标系以屏幕左下角为原点,Y轴向上递增CGDisplayBounds返回的Core Graphics坐标系以屏幕左上角为原点,Y轴向下递增
你可以用系统API完成程序化转换,不用手动计算,这里提供两种可靠方式:
方式一:利用NSScreen的坐标系映射
AppKit的NSScreen自带的坐标系和NSEvent.mouseLocation完全对齐,先找到对应显示设备的NSScreen实例,再完成坐标转换:
import Cocoa func convertCGDisplayPointToMouseCoordinate(displayID: CGDirectDisplayID, cgPoint: CGPoint) -> CGPoint? { // 找到对应DisplayID的NSScreen guard let targetScreen = NSScreen.screens.first(where: { $0.deviceDescription[NSDeviceDescriptionKey("NSScreenNumber")] as? CGDirectDisplayID == displayID }) else { return nil } // 将CGDisplayBounds的点转换为NSScreen的全局坐标(和mouseLocation一致) let screenRelativeY = targetScreen.frame.maxY - cgPoint.y return CGPoint(x: cgPoint.x, y: screenRelativeY) }
方式二:使用Core Graphics的变换API
如果需要处理屏幕旋转等复杂场景,Core Graphics提供了专门的变换函数来处理显示坐标和全局坐标的转换:
import CoreGraphics import Cocoa func convertCGDisplayPointToMouseCoordinate(displayID: CGDirectDisplayID, cgPoint: CGPoint) -> CGPoint { // 获取显示设备的变换矩阵(处理旋转、翻转等) let displayTransform = CGDisplayGetDisplayTransform(displayID) // 将点转换为显示空间坐标 let displaySpacePoint = CGDisplayConvertPointToDisplaySpace(displayID, cgPoint) // 应用变换得到与mouseLocation一致的坐标 return CGPointApplyAffineTransform(displaySpacePoint, displayTransform) }
调用示例:
// 获取主屏幕的DisplayID let mainDisplayID = CGMainDisplayID() // 从CGDisplayBounds中取一个测试点 let boundsPoint = CGPoint(x: 100, y: 100) // 转换为mouseLocation格式的坐标 if let convertedPoint = convertCGDisplayPointToMouseCoordinate(displayID: mainDisplayID, cgPoint: boundsPoint) { print(convertedPoint) // 输出坐标与NSEvent.mouseLocation格式完全一致 }
内容的提问来源于stack exchange,提问作者Khang
相关产品推荐
相关产品推荐

