我正在尝试存储NSView当前上下文并稍后再次将其绘制到NSView。我想知道最快和最有效的方法是什么?
答案 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
。