2012-12-07 34 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子類能夠繪製到位圖上下文,但除此之外,它沒有問題。 –