CGContextRef没有绘图

时间:2013-03-04 18:52:54

标签: objective-c macos drawing

我正在尝试为我的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)圈子完美绘制

1 个答案:

答案 0 :(得分: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];
}