Draw only the modified NSView area

I am trying to make NSView effective, even when resizing. According to the docs for -drawRect:, I can use -getRectsBeingDrawn:count:to figure out what exactly needs to be redrawn and only redraw. In addition, if I want to have save content while preserving the live image, I must return YES from -preservesContentDuringLiveResizeand override -setFrameSize:and use -getRectsExposedDuringLiveResize:count:it to determine what to mark as a display need. But with live resizing of the window inside, the -drawRect:method -getRectsBeingDrawn:count:still returns all the borders of the NSView, and not just the newly opened part of the view. I confirm this by subclassing NSView below (auto-size to always fill the window) and dragging the bottom edge of the window down.

- (void) drawRect:(NSRect)dirtyRect {
    const NSRect* rects;
    NSInteger count;
    [self getRectsBeingDrawn:&rects count:&count];

    for (int i = 0; i < count; i++) {
        NSRect r = rects[i];
        [[[NSColor greenColor] colorWithAlphaComponent:0.5] drawSwatchInRect:r];
    }
}

- (BOOL) preservesContentDuringLiveResize {
    return YES;
}

- (BOOL) isOpaque {
    return YES;
}

- (void) setFrameSize:(NSSize)newSize {
    [super setFrameSize:newSize];

    if ([self inLiveResize]) {
        NSRect rects[4];
        NSInteger count;
        [self getRectsExposedDuringLiveResize:rects count:&count];

        for (int i = 0; i < count; i++) {
            NSRect r = rects[i];
            [self setNeedsDisplayInRect:r];
        }
    }
    else {
        [self setNeedsDisplay:YES];
    }
}
+4

Source: https://habr.com/ru/post/1539113/


All Articles