目标c - cgcontext不绘图



我想为我的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) 圆圈被完美地绘制!

mouseMoved不是正确的地方画任何东西,除非你画在屏幕外的缓冲区。如果你要在屏幕上绘制,保存 point 和其他必要的数据,调用[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];
}

最新更新