【发布时间】:2010-12-31 00:03:55
【问题描述】:
我正在使用 NSView 来托管多个 Core Animation CALayer 对象。我想要做的是获取视图当前状态的快照作为位图图像。
这对于普通的NSView 使用这样的东西相对简单:
void ClearBitmapImageRep(NSBitmapImageRep* bitmap) {
unsigned char* bitmapData = [bitmap bitmapData];
if (bitmapData != NULL)
bzero(bitmapData, [bitmap bytesPerRow] * [bitmap pixelsHigh]);
}
@implementation NSView (Additions)
- (NSBitmapImageRep*)bitmapImageRepInRect:(NSRect)rect
{
NSBitmapImageRep* imageRep = [self bitmapImageRepForCachingDisplayInRect:rect];
ClearBitmapImageRep(imageRep);
[self cacheDisplayInRect:rect toBitmapImageRep:imageRep];
return imageRep;
}
@end
但是,当我使用这段代码时,Core Animation 层没有被渲染。
我已经调查了CARenderer,因为它似乎可以满足我的需要,但是我无法让它渲染我现有的图层树。我尝试了以下方法:
NSOpenGLPixelFormatAttribute att[] =
{
NSOpenGLPFAWindow,
NSOpenGLPFADoubleBuffer,
NSOpenGLPFAColorSize, 24,
NSOpenGLPFAAlphaSize, 8,
NSOpenGLPFADepthSize, 24,
NSOpenGLPFANoRecovery,
NSOpenGLPFAAccelerated,
0
};
NSOpenGLPixelFormat *pixelFormat = [[NSOpenGLPixelFormat alloc] initWithAttributes:att];
NSOpenGLView* openGLView = [[NSOpenGLView alloc] initWithFrame:[self frame] pixelFormat:pixelFormat];
NSOpenGLContext* oglctx = [openGLView openGLContext];
CARenderer* renderer = [CARenderer rendererWithCGLContext:[oglctx CGLContextObj] options:nil];
renderer.layer = myContentLayer;
[renderer render];
NSBitmapImageRep* bitmap = [oglView bitmapImageRepInRect:[oglView bounds]];
但是,当我这样做时,我得到了一个例外:
CAContextInvalidLayer -- layer <CALayer: 0x1092ea0> is already attached to a context
我猜这一定是因为层树托管在我的NSView 中,因此附加到它的上下文中。我不明白如何将层树与NSView 分离以将其渲染为位图,在这种情况下创建重复的层树并非易事。
还有其他方法可以让CALayers 渲染到位图吗?我在任何地方都找不到任何示例代码来执行此操作,事实上我根本找不到CARenderer 的任何示例代码。
【问题讨论】:
标签: objective-c cocoa core-animation bitmap rendering