NSView drawRect 是否会干扰子视图?

4
我有一个NSView,我使用draw 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];
}

你能发一下你自定义的 drawRect: 吗? - jscs
发布了drawRect方法。谢谢。 - user635064
2个回答

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]

谢谢回复,但那个方法并没有起作用。另外,我想你是指saveGraphicsState和restoreGraphicsState吧?再次感谢。 - user635064
@user635064:是的,我就是这个意思,谢谢;我今天一整天都在打错字。虽然它并没有直接解决你的问题,但你仍应该使用它,因为它可以防止其他问题的出现。 - jscs

0
你确定那些按钮实际上是子视图,而不仅仅是放置在你绘制的视图上吗?

谢谢回复。是的,我确定问题出在哪里,但我知道如何解决它。请再次阅读我的原始问题,因为我已经编辑并详细解释了问题。再次感谢。 - user635064

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接