首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >CGContextRef不绘图

CGContextRef不绘图
EN

Stack Overflow用户
提问于 2013-03-04 18:52:54
回答 1查看 475关注 0票数 0

我正在为我的Mac应用程序画一个圆圈。“守则”是:

代码语言:javascript
复制
- (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) ,那么这个圆圈就完美地绘制了

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-03-04 18:56:38

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

而且,我看不出有什么理由使用CGContextRef,而更多的是“友好”的NSGraphicsContext。不过,这是味道的问题。

绘图代码的一个示例:

代码语言:javascript
复制
- (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];
}
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15208895

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档