0

我正在尝试为我的 Mac 应用程序画一个圆圈。该代码是:

- (void)mouseMoved:(NSEvent*)theEvent {
    NSPoint thePoint = [[self.window contentView] convertPoint:[theEvent locationInWindow] fromView:nil];
    NSLog(@"mouse moved: %f % %f",thePoint.x, thePoint.y);

    CGRect circleRect = CGRectMake(thePoint.x, thePoint.y, 20, 20);
    CGContextRef context = [[NSGraphicsContext currentContext] graphicsPort];
    CGContextSetRGBFillColor(context, 0, 0, 255, 1.0);
    CGContextSetRGBStrokeColor(context, 0, 0, 255, 0.5);
    CGContextFillEllipseInRect(context, CGRectMake(circleRect.origin.x, circleRect.origin.y, 25, 25));
    CGContextStrokeEllipseInRect(context, circleRect);
    [self needsDisplay];
}

- (void)mouseMoved:被完美调用,我可以在 NSLog 中看到正确的 x 和 y 坐标。但我没有得到任何圆圈......令人惊讶的是:如果我正在最小化我的应用程序并重新打开它(因此它“更新”NSView),那么圆圈就会完美绘制

4

1 回答 1

4

mouseMoved不是绘制任何东西的正确位置,除非您在屏幕外缓冲区上绘制。如果您要在屏幕上绘制,请保存thePoint和任何其他必要的数据,然后在该方法中调用[self setNeedsDisplay:YES]并绘制。drawRect:(NSRect)rect

此外,我看不出有使用的理由,CGContextRef而有更多的“友好” NSGraphicsContext。虽然,这是品味问题。

绘制代码示例:

- (void)mouseMoved:(NSEvent*)theEvent {
    // thePoint must be declared as the class member
    thePoint = [[self.window contentView] convertPoint:[theEvent locationInWindow] fromView:nil];
    [self setNeedsDisplay:YES];
}

- (void)drawRect:(NSRect)rect
{
    NSRect ovalRect = NSMakeRect(thePoint.x - 100, thePoint.y - 100, 200, 200);
    NSBezierPath* oval = [NSBezierPath bezierPathWithOvalInRect:ovalRect];
    [[NSColor blueColor] set];
    [oval fill];
    [[NSColor redColor] set];
    [oval stroke];
}
于 2013-03-04T18:56:38.987 回答