如何查找鼠标是否在视图上方

Arl*_*son 19 macos cocoa objective-c nsview

我需要找到鼠标位置是否在NSView的rect内.

我会用NSPointInRect(point, rect),但我需要将rect坐标转换为屏幕坐标,我不知道如何.任何帮助将非常感激!

Jon*_*etz 33

这样的事情对你有用:

NSView* myView; // The view you are converting coordinates to
NSPoint globalLocation = [ NSEvent mouseLocation ];
NSPoint windowLocation = [ [ myView window ] convertScreenToBase: globalLocation ];
NSPoint viewLocation = [ myView convertPoint: windowLocation fromView: nil ];
if( NSPointInRect( viewLocation, [ myView bounds ] ) ) {
    // Do your thing here
}
Run Code Online (Sandbox Code Playgroud)

我个人并没有使用这么多局部变量,但希望这会使这个例子更加清晰.

  • locationInWindow可能大部分时间都可以工作.但这来自Apple文档:"使用NSMouseMoved以及可能的其他事件,接收器可以有一个nil窗口(即窗口返回nil).在这种情况下,locationInWindow以屏幕坐标返回事件位置." 所以看起来不依赖于locationInWindow可能会更强大.如果你已经有一个事件,locationInWindow肯定会被使用.即使您还没有事件对象,我的答案中的方法也会起作用. (2认同)

Mat*_*ner 23

使用NSView的convertPoint:fromView:方法,将fromView作为nil,将窗口坐标中的点转换为视图的坐标系.

将鼠标点转换为视图坐标系后,我会使用NSView的鼠标:inRect:方法而不是NSPointInRect,因为前者也会考虑翻转坐标系.

或者,您可以使用跟踪区域对象.

  • 我想补充一点,你应该在`NSView的鼠标中传递'NSRect`参数的`self.bounds`:inRect:`发送`self.frame`将偏移坐标. (2认同)

Rya*_*n H 7

NSView isMousePoint函数对我有用,无需担心任何 CG。

func isMouseInView(view: NSView) -> Bool? {
    if let window = view.window {
        return view.isMousePoint(window.mouseLocationOutsideOfEventStream, in: view.frame)
    }
    return nil
}
Run Code Online (Sandbox Code Playgroud)


aep*_*yus 5

一些使用鼠标的代码:inRect :(推荐方式;考虑翻转坐标)

CGPoint point = [self convertPoint:[event locationInWindow] fromView:nil];
CGRect rect = [self bounds];
if ([self mouse:point inRect:rect]) {
}
Run Code Online (Sandbox Code Playgroud)