首页 > 解决方案 > NSGraphicsContext becomes NULL after setting CAMetalLayer

问题描述

I trying to move my NSView based application to start using GPU with Metal. So, I added a CAMetalLayer using like this:

[self setWantsLayer:YES];
self.layerContentsRedrawPolicy = NSViewLayerContentsRedrawDuringViewResize;

And make the backing layer, like this:

- (CALayer*)makeBackingLayer
{
    id <MTLDevice> device = MTLCreateSystemDefaultDevice();
    CAMetalLayer *backingLayer   = [CAMetalLayer layer];
    backingLayer.opaque          = YES;
    backingLayer.device          = device;
    backingLayer.pixelFormat     = MTLPixelFormatBGRA8Unorm;
    backingLayer.framebufferOnly = YES;

    [backingLayer setDelegate:self];
    return backingLayer;
}

I write all this code in my CustomNSView class is inherited from a CustomParentNSView class which uses NSGraphicsContext to draw some things on the screen. Now, since I am moving CustomNSView to a layer backed NSView, when I try to call:

[NSGraphicsContext currentContext]

This returns NULL.

  1. Should this be NULL for layer backed NSViews?

I also tried investigating where in the previous implementation NSGraphicsContext was getting generated, and it turns out, my application was setting it nowhere. NSView was itself setting the NSGraphicsContext from somewhere inside of displayIfNeeded, before calling drawRect.

  1. Can I still use NSGraphicsContext to render to NSView, even when it is layer backed?

Thanks!

标签: macoscalayernsviewmetal

解决方案


推荐阅读