我正在为我的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) ,那么这个圆圈就完美地绘制了!
发布于 2013-03-04 18:56:38
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];
}https://stackoverflow.com/questions/15208895
复制相似问题