缓存NSView上下文

时间:2012-09-21 09:31:52

标签: objective-c cocoa nsview cgcontext

我正在尝试存储NSView当前上下文并稍后再次将其绘制到NSView。我想知道最快和最有效的方法是什么?

1 个答案:

答案 0 :(得分:1)

您可以将内容绘制到NSImage并稍后重新绘制图像,但需要在需要时使缓存无效(这取决于您的视图的作用)。

示例:

@interface SOCacheView : NSView

@end

@implementation SOCacheView
{
    NSImage *_cache;
}

- (void)drawRect:(NSRect)dirtyRect
{
    [super drawRect:dirtyRect];

    if (!_cache) [self prepareImage];

    [_cache drawAtPoint:NSZeroPoint fromRect:self.bounds operation:NSCompositeSourceOver fraction:1.0];
}

- (void)prepareImage
{
    _cache = [[NSImage alloc] initWithSize:self.bounds.size];
    [_cache lockFocus];

    // do the drawing here...

    [[NSColor blueColor] setFill];
    NSRectFill(NSMakeRect(0, 0, NSWidth(self.bounds)/2, NSHeight(self.bounds)));
    [[NSColor redColor] setFill];
    NSRectFill(NSMakeRect(NSWidth(self.bounds)/2, 0, NSWidth(self.bounds)/2, NSHeight(self.bounds)));

    [_cache unlockFocus];
}

要使缓存的绘图无效,只需将_cache设置为nil

Here's a sample project让你玩