NSScrollView messes up NSGradient (corruption)

219 Views Asked by At

I have a custom box that I've made that is a subclass of NSBox. I override the drawRect: method and draw a gradient in it like this (assuming I already have a start & end color):

-(void)drawRect:(NSRect)dirtyRect {
    NSGradient *gradient = [[NSGradient alloc] initWithStartingColor:start endingColor:end];
    [gradient drawInRect:dirtyRect angle:270];
    [gradient release];
}

Now this box is added as a subview of a prototype view for a NSCollectionView. In the view's original state it looks like this:

enter image description here

And after scrolling the view out of sight and back in again, it looks like this:

enter image description here

Why is my gradient getting corrupted like that, and how can I fix it? Thanks!

2

There are 2 best solutions below

4
On BEST ANSWER

Your problem is you're drawing in dirtyFrame, not the entire rectangle of the box. I have no idea if this is correct, but try this:

-(void)drawRect:(NSRect)dirtyRect {
    NSGradient *gradient = [[NSGradient alloc] initWithStartingColor:start endingColor:end];
    [gradient drawInRect:[self bounds] angle:270];
    [gradient release];
}
1
On

That dirtyRect argument doesn’t necessarily represent the entire box. If Cocoa decides that only a subframe of the original frame needs (re)drawing, dirtyRect represents only that subframe. If you’ve drawn a gradient for the entire frame and then (re)draw the same gradient for a subframe, it's likely they won't match.

Try:

[gradient drawInRect:[self bounds] angle:270];

instead.

One further note: it looks like your gradient object could be cached instead of being created/released inside -drawRect:.