2012-12-07 33 views
0

我想制作一个自定义动画替换NSView与另一个。 因此,我需要在屏幕上出现NSView图像。捕获离线NSView到NSImage

视图可能包含层和NSOpenGLView子视图,并像initWithFocusedViewRectbitmapImageRepForCachingDisplayInRect因此标准选项不会在这种情况下很好地工作(它们层或OpenGL内容以及在我的实验)。

我在寻找类似CGWindowListCreateImage的东西,它能够“捕捉”包括图层和OpenGL内容的离线NSWindow

有什么建议吗?

回答

2

我创建了这个类别:

@implementation NSView (PecuniaAdditions) 

/** 
* Returns an offscreen view containing all visual elements of this view for printing, 
* including CALayer content. Useful only for views that are layer-backed. 
*/ 
- (NSView*)printViewForLayerBackedView; 
{ 
    NSRect bounds = self.bounds; 
    int bitmapBytesPerRow = 4 * bounds.size.width; 

    CGColorSpaceRef colorSpace = CGColorSpaceCreateWithName(kCGColorSpaceSRGB); 
    CGContextRef context = CGBitmapContextCreate (NULL, 
                bounds.size.width, 
                bounds.size.height, 
                8, 
                bitmapBytesPerRow, 
                colorSpace, 
                kCGImageAlphaPremultipliedLast); 
    CGColorSpaceRelease(colorSpace); 

    if (context == NULL) 
    { 
     NSLog(@"getPrintViewForLayerBackedView: Failed to create context."); 
     return nil; 
    } 

    [[self layer] renderInContext: context]; 
    CGImageRef img = CGBitmapContextCreateImage(context); 
    NSImage* image = [[NSImage alloc] initWithCGImage: img size: bounds.size]; 

    NSImageView* canvas = [[NSImageView alloc] initWithFrame: bounds]; 
    [canvas setImage: image]; 

    CFRelease(img); 
    CFRelease(context); 
    return canvas; 
} 

@end 

此代码主要用于包含分层子视图打印NSViews。也可以帮助你。

+0

该解决方案需要NSOpenGLView子类能够绘制到位图上下文,但除此之外,它没有问题。 –