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 に答える