sudo rm -rf
sudo rm -rf

Reputation: 29524

NSScrollView messes up NSGradient (corruption)

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!

Upvotes: 2

Views: 210

Answers (2)

icktoofay
icktoofay

Reputation: 129109

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];
}

Upvotes: 1

user557219
user557219

Reputation:

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:.

Upvotes: 3

Related Questions