自定义NSView在其上方绘制控件

时间:2013-09-28 19:45:21

标签: objective-c macos drawing nsview

我有一个NSView的自定义子类,在其中绘制一个圆角矩形网格。这个NSView放置了界面构建器,在它之上我有一些NSButton s。

问题在于,有时当重新绘制视图时(即,当我点击它上面的按钮时),它会重新绘制一些意图保持在顶部的按钮。当发生这种情况时,只有较小的圆形部分出现在按钮上,而不是在循环之前绘制的背景部分。

这是代码形式drawRect:

[NSGraphicsContext saveGraphicsState];

NSBezierPath *path = [NSBezierPath bezierPathWithRect:self.bounds];
[[NSColor grayColor] set];
[path fill];

[NSGraphicsContext restoreGraphicsState];

for( int r = 0; r < 15; r++ ){
    for( int c = 0; c < 15; c++ ) {

        [NSGraphicsContext saveGraphicsState];

        // Draw shape
        NSRect rect = NSMakeRect(20 * c, 20 * r, 15, 15);
        NSBezierPath *roundedRect = [NSBezierPath bezierPathWithRoundedRect: rect xRadius:1 yRadius:1];

        [roundedRect setClip];

        // Fill
        [[NSColor colorWithCalibratedHue:0 saturation:0 brightness:0.3 alpha:1] set];
        [roundedRect fill];


        // Stroke
        [[NSColor colorWithCalibratedHue:0 saturation:0 brightness:0.5 alpha:1] set];
        [roundedRect setLineWidth:2.0];
        [roundedRect stroke];

        [NSGraphicsContext restoreGraphicsState];

    }
}

这是一个截图: Screenshot

更新:简化了代码,添加了屏幕截图。

2 个答案:

答案 0 :(得分:0)

mac存在重叠兄弟视图的问题。它在10.6之前没有用,它仍然不常用。

使用适当的superview / subview hierachy

答案 1 :(得分:0)

好的,我只是通过移除setClip并找到另一种绘制内部笔划的方法来解决这个问题。

我确信在使用setClip的同时解决这个问题是可能的,但这次这个解决方案对我来说很合适。