3

我是编程、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];
}

我不知道怎么继续,有什么建议吗?谢谢!

4

1 回答 1

5

您不应该在该-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

当您收到鼠标按下事件时,您只需存储鼠标按下的位置。绘图是在-drawLastMousePoint您调用-drawRect:方法时完成的。由于您知道在单击鼠标时需要重绘,因此您调用-setNeedsDisplay:通知视图它需要重绘。请注意,重绘不会立即发生,而是会在下一次通过运行循环时发生。换句话说,您是在说“嘿,发生了一些变化,我需要重新绘制视图的内容。请-drawRect:尽快再次调用!”

另一个注意事项:+[NSEvent mouseLocation]实际上是为在事件流之外获取当前鼠标位置而设计的。通常,在-mouseDown:方法中,您调用作为参数-locationInWindow传递NSEvent的方法。如果您需要转换为本地/视图坐标,您应该调用[self convertPoint:[theEvent locationInWindow] fromView:nil];.

于 2013-02-21T22:37:39.563 回答