7

我可以[NSEvent mouseLocation]用来获取光标的位置,但这给了我屏幕坐标。当光标在视图中时,如何获取光标相对于视图的坐标?我搜索了 Apple 文档,但找不到答案。

如果它有所作为,我将希望不断检索鼠标位置,因为它将在每次帧更新中使用。

4

3 回答 3

11

为了完整起见,有一种直接的方法可以在窗口坐标中获取鼠标位置(使用 NSWindow)。根据您的窗口布局,这可能等同于视图的坐标。

NSWindow *myWindow;
NSPoint mousePos;
...
mousePos = [myWindow mouseLocationOutsideOfEventStream];

返回的坐标是窗口坐标,因此如果鼠标位于窗口的左侧/下方,则返回负值。如果鼠标在窗口的右侧/上方,则坐标将超过窗口的大小。

于 2014-11-10T23:21:16.403 回答
8
NSPoint myPoint = 
    [myView convertPoint:[myWindow convertScreenToBase:[NSEvent mouseLocation]]
                fromView:nil];
于 2011-09-18T19:48:01.010 回答
7
- (void)mouseMoved:(NSEvent *)event
{
    NSPoint locationInView = [self convertPoint:[event locationInWindow]
                                       fromView:nil];
}

还要确保您已启用 mouseMoved 事件:

[window setAcceptsMouseMovedEvents:YES];
于 2011-09-18T19:50:03.597 回答