2

我有一个自定义 NSView,NSScrollView它位于NSSplitView. 自定义视图使用以下绘图代码:

- (void)drawRect:(NSRect)dirtyRect {
    NSGraphicsContext *ctx = [NSGraphicsContext currentContext];
    [ctx saveGraphicsState];

    // Rounded Rect
    NSRect rect = [self bounds];
    NSRect pathRect = NSMakeRect(rect.origin.x + 3, rect.origin.y + 6, rect.size.width - 6, rect.size.height - 6);
    NSBezierPath *path = [NSBezierPath bezierPathWithRoundedRect:pathRect cornerRadius:kDefaultCornerRadius];

    // Shadow
    [NSShadow setShadowWithColor:[NSColor colorWithCalibratedWhite:0 alpha:0.66]
                      blurRadius:4.0
                          offset:NSMakeSize(0, -3)];     
    [[NSColor colorWithCalibratedWhite:0.196 alpha:1.0] set];
    [path fill];
    [NSShadow clearShadow];


    // Background Gradient
    NSGradient *gradient = [[NSGradient alloc] initWithStartingColor:[UAColor darkBlackColor] endingColor:[UAColor lightBlackColor]];
    [gradient drawInBezierPath:path angle:90.0];
    [gradient release];


    // Image
    [path setClip];
    NSRect imageRect = NSMakeRect(pathRect.origin.x, pathRect.origin.y, pathRect.size.height * kLargeImageRatio, pathRect.size.height);
    [self.image drawInRect:imageRect
                  fromRect:NSZeroRect
                 operation:NSCompositeSourceAtop
                  fraction:1.0];

    [ctx restoreGraphicsState];

    [super drawRect:dirtyRect];
}

我已经尝试了每一种不同的类型,operation但图像仍然绘制在另一半的顶部,NSSplitView所以:

在此处输入图像描述

…而不是在NSScrollView. 我认为这与绘制所有内容而不是dirtyRect唯一有关,但我不知道如何编辑图像绘制代码以仅绘制位于dirtyRect. 我怎样才能防止它在顶部绘制,或者只为这个 NSImage 绘制脏矩形?

4

1 回答 1

1

我终于明白了。我不知道它是否是最优的,但我会在进行性能测试时发现。我只需要使用 找出图像 rect 和脏 rect 的交集NSIntersectionRect,然后找出NSImage要为drawInRect:fromRect:operation:fraction:调用绘制的子部分。

这是重要的部分:

    NSRect imageRect = NSMakeRect(pathRect.origin.x, pathRect.origin.y, pathRect.size.height * kLargeImageRatio, pathRect.size.height);
    [self.image setSize:imageRect.size];

    NSRect intersectionRect = NSIntersectionRect(dirtyRect, imageRect);
    NSRect fromRect = NSMakeRect(intersectionRect.origin.x - imageRect.origin.x,
                                 intersectionRect.origin.y - imageRect.origin.y,
                                 intersectionRect.size.width,
                                 intersectionRect.size.height);
    [self.image drawInRect:intersectionRect
                  fromRect:fromRect
                 operation:NSCompositeSourceOver
                  fraction:1.0];
于 2011-02-25T00:18:45.140 回答