Metal 开发教程(二)

https://developer.apple.com/documentation/quartzcore/cametallayer?language=objc#3385893

 CAMetalLayer:Metal 渲染和屏幕显示的核心动画layer。当你想使用Metal渲染layer的内容时可使用CAMetalLayer。要在一个view中渲染时可以考虑使用MTKView,MTKView会自动包装CAMetalLayer并提供高级的抽象。

CAMetalLayer 创建了一个Metal drawable (CAMetalDrawable)的对象池,若要更改layer的内容,请向layer请求drawable对象,进行渲染,然后更新layer的内容以指向新的drawable对象。调用nextDrawable方法获取一个drawable对象。

CAMetalLayer *metalLayer = (CAMetalLayer*)self.layer;
id<CAMetalDrawable> *drawable = [metalLayer nextDrawable]; MTLRenderPassDescriptor *renderPassDescriptor = [MTLRenderPassDescriptor renderPassDescriptor]; renderPassDescriptor.colorAttachments[0].texture = drawable.texture; renderPassDescriptor.colorAttachments[0].loadAction = MTLLoadActionClear; renderPassDescriptor.colorAttachments[0].clearColor = MTLClearColorMake(0.0,0.0,0.0,1.0); ...

只有当drawable没有在屏幕上显示,并且没有强引用的情况下layer才能重用drawable。当调用nextDrawable方法没有可用的drawable时,系统将会一直等待直到有可用的drawable。为了避免app卡顿,请仅在需要时请求新的drawable,并在使用完成后尽快释放相应的引用。在检索新的drawable之前,您可以在CPU上执行其他工作,或者向GPU提交不需要drawable的命令。然后,获取drawable并对命令缓冲区进行编码和渲染,如上所述。提交此命令缓冲区后,释放对drawable的所有强引用。如果不正确释放drawables,则该层将耗layer的drawables,以后对nextDrawable的调用将返回nil。不要显示的释放drawable,应该使用autorelease块来释放。

- (void)drawInMTKView:(MTKView *)view {
    @autoreleasepool {
        [self render:view];
    }
}
 

上面的代码会立即释放drawable,并避免多个drawable可能出现的死锁情况。提交屏幕上的渲染过程后,请尽快释放drawables。

猜你喜欢

转载自www.cnblogs.com/cadstudy/p/12466078.html