【问题标题】:Capturing an offline NSView to an NSImage将离线 NSView 捕获到 NSImage
【发布时间】:2012-12-07 09:24:29
【问题描述】:

我正在尝试制作自定义动画以将 NSView 替换为另一个。 出于这个原因,我需要在 NSView 出现在屏幕上之前获取它的图像。

视图可能包含图层和NSOpenGLView 子视图,因此initWithFocusedViewRectbitmapImageRepForCachingDisplayInRect 等标准选项在这种情况下效果不佳(在我的实验中它们可以很好地分层或OpenGL 内容)。

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

有什么建议吗?

【问题讨论】:

    标签: cocoa drawing core-animation calayer nsview


    【解决方案1】:

    我为此创建了一个类别:

    @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
    

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

    【讨论】:

    • 这个解决方案需要 NSOpenGLView 子类能够绘制到位图上下文,但除此之外,它很好。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多