开发者

NSView drawRect interfering with subviews?

I have an nsview and i use draw rect to draw an image for background. It also has 3 subviews nsbuttons. 开发者_StackOverflow中文版The problem is, whenever the mouse is down on a button, the other buttons disappear. But when I remove the draw rect method, this doesn't happen. So I am guessing this has to do with the draw rect method for drawing images.

How can I avoid this? Thanks.

EDIT: Ok, i figured out where the problem is. Basically, I have an NSMenuItem, and I am putting a view inside it with 3 buttons. But in NSMenu, at the top, there's a padding of 4 pixels. So, basically, to remove that padding I used the solution provided here: Gap above NSMenuItem custom view

From the solution there's a line in the drawRect method:

[[NSBezierPath bezierPathWithRect:fullBounds] setClip];

The moment, i remove this line, and the button behave properly. But then, the padding on top doesn't go away.

Here's my 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];
}


The solution to the linked question doesn't include saving and restoring the graphics state, which is a good idea when you are modifying one that you didn't create. Give this a try:

- (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]


Are you sure that those buttons are actually subviews, and not just placed over the view you're drawing?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜