2015-05-28 68 views
2

我的应用程序中有一个NSView的自定义子类。 我想知道视图中与鼠标点击相关的确切点。 (即,不是相对于窗口原点,而是相对于自定义视图原点)。什么是计算鼠标点击的正确方法

我一直用这个,已经完美工作:

-(void)mouseDown:(NSEvent *)theEvent 
{ 
    NSPoint screenPoint = [NSEvent mouseLocation]; 
    NSPoint windowPoint = [[self window] convertScreenToBase:screenPoint]; 
    NSPoint point = [self convertPoint:windowPoint fromView:nil]; 

    _pointInView = point; 

    [self setNeedsDisplay:YES]; 
} 

但现在我得到一个警告,convertScreenToBase已被弃用,使用convertRectFromScreen代替。然而,我无法从convertRectFromScreen获得相同的结果,无论如何,我对一个点感兴趣,而不是一个正确的!

我应该如何正确替换上面的弃用代码? 在此先感谢!

回答

1

我找到了解决办法:

NSPoint screenPoint = [NSEvent mouseLocation]; 
NSRect screenRect = CGRectMake(screenPoint.x, screenPoint.y, 1.0, 1.0); 
NSRect baseRect = [self.window convertRectFromScreen:screenRect]; 
_pointInView = [self convertPoint:baseRect.origin fromView:nil]; 
+0

与Max的答案唯一真正的区别似乎是使用1.0而不是0来表示矩形尺寸。 – Kenny

2

我用一个窗口制作了一个示例项目,并测试了“旧”和新的场景。两种情况下的结果都是一样的。

你必须做一个额外的步骤:用screenPoint作为原点创建一个简单的矩形。然后使用新的返回矩形的原点。

这是新代码:

-(void)mouseDown:(NSEvent *)theEvent 
{ 
    NSPoint screenPoint = [NSEvent mouseLocation]; 
    NSRect rect = [[self window] convertRectFromScreen:NSMakeRect(screenPoint.x, screenPoint.y, 0, 0)]; 

    NSPoint windowPoint = rect.origin; 
    NSPoint point = [self convertPoint:windowPoint fromView:nil]; 

    _pointInView = point; 

    [self setNeedsDisplay:YES]; 
} 

我希望我能够帮到你!

+0

嗯。你的代码和我的代码给出了完全不同的结果! [rect origin]应该是rect.origin,因为NSRect不是一个类。 – Kenny

+0

你是对的,rect.origin,那是我的错。我会再看看它! – mangerlahn

+0

视图位于哪里?它可能在翻转的坐标系中 – mangerlahn

4

这条线从您的代码:

NSPoint screenPoint = [NSEvent mouseLocation]; 

获取鼠标光标的位置不同步的事件流。这不是你正在处理的事件的位置,这是过去很短的时间;这是光标现在的位置,这意味着你可能会跳过一些重要的东西。您应该几乎总是使用与事件流同步的位置。

为此,请使用您的方法接收的theEvent参数。 NSEvent有一个locationInWindow属性,该属性已被转换为接收它的窗口的坐标。这消除了您对其进行转换的需求。

NSPoint windowPoint = [theEvent locationInWindow];  

将窗口位置转换为视图坐标系的代码很好。

相关问题