gpt4 book ai didi

objective-c - 通过鼠标事件绘制到 NSView 中

转载 作者:搜寻专家 更新时间:2023-10-30 20:03:02 24 4
gpt4 key购买 nike

我是编程新手,objective-c(和 stackoverflow)。我正在慢慢学习和前进 ;) 但后来我遇到了一个问题,谷歌无法解决。我有一个窗口和一个 NSview,然后添加了一个应该将坐标绘制到我的 View 中的鼠标事件,但它没有。有趣的是:当鼠标移到我的应用程序窗口的窗口按钮上时它被绘制...

- (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];
}

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

最佳答案

您不应该在 -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: 通知 View 需要重绘。请注意,重绘不会立即发生,而是会在下一次运行循环中发生。换句话说,你是说“嘿,有些东西变了,我需要重新绘制 View 的内容。请尽快再次调用 -drawRect:!”

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

关于objective-c - 通过鼠标事件绘制到 NSView 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15012994/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com