NSView drawRect干扰子视图?

时间:2011-04-21 15:00:02

标签: objective-c cocoa nsview drawrect nsbutton

我有一个nsview,我使用绘制rect来绘制背景图像。它还有3个子视图nsbuttons。问题是,只要鼠标按下按钮,其他按钮就会消失。但是当我删除draw rect方法时,这不会发生。所以我猜这与绘制图像的draw rect方法有关。

我该如何避免这种情况? 感谢。

编辑: 好的,我想出了问题所在。基本上,我有一个NSMenuItem,我用3个按钮在其中放置一个视图。但在NSMenu中,顶部有一个4像素的填充。所以,基本上,为了删除填充,我使用了这里提供的解决方案: Gap above NSMenuItem custom view

从解决方案中,drawRect方法中有一行:

[[NSBezierPath bezierPathWithRect:fullBounds] setClip];

此刻,我删除了这一行,按钮表现正常。但是,顶部的填充物不会消失。

这是我的drawRect:

- (void) drawRect:(NSRect)dirtyRect {

    [[NSGraphicsContext currentContext] saveGraphicsState];

    NSRect fullBounds = [self bounds];
    fullBounds.size.height += 4;
    [[NSBezierPath bezierPathWithRect:fullBounds] setClip];

    NSImage *background = [NSImage imageNamed:@"bg.png"];
    [background drawInRect:fullBounds fromRect:NSZeroRect operation:NSCompositeCopy fraction:100.0];

    [[NSGraphicsContext currentContext] restoreGraphicsState];
}

2 个答案:

答案 0 :(得分:3)

链接问题的解决方案不包括保存和恢复图形状态,这在您修改未创建的状态时是一个好主意。试一试:

- (void)drawRect:(NSRect)dirtyRect {
   // Save the current clip rect that has been set up for you
   [NSGraphicsContext saveGraphicsState];
   // Calculate your fullBounds rect
   // ...
   // Set the clip rect
   // ...
   // Do your drawing
   // ...
   // Restore the correct clip rect
   [NSGraphicsContext restoreGraphicsState]

答案 1 :(得分:0)

您确定这些按钮实际上是子视图,而不只是放在您正在绘制的视图上吗?

相关问题