2
votes

I'm having a problem with custom drawing NSView using as documentView of a NSScrollView.

Here is my drawRect: code:

- (void)drawRect:(NSRect)dirtyRect
{
    [[NSColor lightGrayColor] set];
    NSRectFill(self.frame); // Fill entire frame

    [[NSColor grayColor] set];
    [NSBezierPath setDefaultLineWidth:1];

    float y = 0.0f;
    while (y <= self.frame.size.height) {
        [NSBezierPath strokeLineFromPoint:NSMakePoint(0.0f, y) toPoint:NSMakePoint(self.frame.size.width, y)];
        y += 50.0f;
    }

    float x = 0.0f;
    while (x <= self.frame.size.width) {
        [NSBezierPath strokeLineFromPoint:NSMakePoint(x, 0.0f) toPoint:NSMakePoint(x, self.frame.size.height)];
        x += 50.0f;
    }
}

Drawing a grid

Everything is OK when I scroll the view rightward, but I see strange lines when I scroll the view leftward.

enter image description here

I think this is a cached image buffer or something but I couldn't get why this occurs because I fill a rect which covers entire frame.

What causes this problem? How can I solve it? Thanks.

2

2 Answers

1
votes

I know this is an old question but I just encountered the same problem and I managed to fix it.

the drawRect method has one argument, a (CGRect) dirtyRect. My mistake was that I used the dirtyRect to check for the boundaries to draw on, just like on iOS. But I discovered that this CGRect is called 'dirty' for a reason. It specifies the region that the OS wants you to redraw. This sometimes isn't the entire frame of the NSView, but a part of it. This allows you to make really fast optimized code that does't draw more than it has to.

My solution was to ignore the dirtyRect and instead simply use self.bounds for drawing.

0
votes

Basically, you're drawing on top of the old content. So, essentially, you need to clear it somehow.

One way is

[[NSColor clearColor] set];
NSRectFill(_bounds);

You may want something more precise or not.