fw2*_*601 3 macos objective-c mouseevent nsview
我是编程,objective-c(和stackoverflow)的新手.我正在慢慢地学习和前进;)然后我遇到了一个谷歌无法解决的问题.我有一个窗口和一个NSview,然后添加了一个鼠标事件,应该将坐标绘制到我的视图中,但事实并非如此.有趣的是:当鼠标移动到我的应用程序窗口的窗口按钮时绘制它...
- (void)drawRect:(NSRect)dirtyRect {
NSPoint imagePos = NSMakePoint(0, 0);
NSImage *aImage = [NSImage imageNamed:@"mw_bg01.png"];
[aImage dissolveToPoint:imagePos fraction:1.0];
}
- (void)mouseDown:(NSEvent*)theEvent;{
mouseLoc = [NSEvent mouseLocation];
mousePosX = mouseLoc.x;mousePosY = mouseLoc.y;
NSString* mouseString = [NSString stringWithFormat:@"%d", mousePosX];
NSPoint textPoint = NSMakePoint(5, 5);
NSMutableDictionary *textAttrib = [[NSMutableDictionary alloc] init];
[textAttrib setObject:[NSFont fontWithName:@"Helvetica Light" size:10]
forKey:NSFontAttributeName];
[textAttrib setObject:[NSColor grayColor] forKey:NSForegroundColorAttributeName];
[mouseString drawAtPoint:textPoint withAttributes:textAttrib];
}
Run Code Online (Sandbox Code Playgroud)
我不知道怎么回事,有什么建议吗?谢谢!
你不应该在-mouseDown:方法中绘图.相反,您必须完成所有绘图-drawRect:(或您调用的方法-drawRect:).尝试这样的事情:
@interface MyView ()
@property NSPoint lastMousePoint;
@end
@implementation MyView
- (void)drawLastMousePoint
{
NSString *mouseString = NSStringFromPoint(self.lastMousePoint);
NSPoint textPoint = NSMakePoint(5, 5);
NSMutableDictionary *textAttrib = [[NSMutableDictionary alloc] init];
[textAttrib setObject:[NSFont fontWithName:@"Helvetica Light" size:10]
forKey:NSFontAttributeName];
[textAttrib setObject:[NSColor grayColor] forKey:NSForegroundColorAttributeName];
[mouseString drawAtPoint:textPoint withAttributes:textAttrib];
}
- (void)drawRect:(NSRect)dirtyRect
{
NSPoint imagePos = NSMakePoint(0, 0);
NSImage *aImage = [NSImage imageNamed:@"mw_bg01.png"];
[aImage dissolveToPoint:imagePos fraction:1.0];
[self drawLastMousePoint];
}
- (void)mouseDown:(NSEvent*)theEvent;
{
self.lastMousePoint = [theEvent locationInWindow];
[self setNeedsDisplay:YES];
}
@end
Run Code Online (Sandbox Code Playgroud)
当您收到鼠标按下事件时,只需将鼠标的位置存储下来即可.完成绘图-drawLastMousePoint,您可以在其中调用-drawRect:方法.由于您知道在单击鼠标时需要重绘,因此您调用-setNeedsDisplay:以通知视图需要重绘.请注意,重绘不会立即发生,而是在下次通过运行循环时发生.换句话说,你说"嘿,有些事情发生了变化,我需要再次提取我的观点内容.请-drawRect:尽快再次致电!"
另一个注意事项:+[NSEvent mouseLocation]实际上是为了将当前鼠标位置放在事件流之外.通常,在-mouseDown:方法调用-locationInWindow上NSEvent传递的参数的方法.如果您需要转换为本地/视图坐标,您应该致电[self convertPoint:[theEvent locationInWindow] fromView:nil];.