Let’s see what are the differences between using the newer
MetalKit framework as opposed to using the earlier
Metal framework. They are both still coexisting, however,
MetalKit introduces a few powerful features such as:
textureloading (even asynchronous loading with a few lines of code).
- Efficient data transfer between
Model I/Omeshes and
MTKView- a convenient
Metal-awareview (we’ll look at it in more detail).
I will start by reminding you how our first program looked like in chapter 1:
That was it! Simple and elegant way to clear your background color to a custom color of your choice. Now let’s switch to using the
Metal framework which does not have the
MTKView so we will need to subclass
You will immediately notice a few errors signaling that the following properties are not provided to us by default anymore:
- a device
- a drawable
- a render pass descriptor
Let’s fix that. First, since
NSView is not
Metal-aware we need to create a
CAMetalLayer and tell
NSView to use it as its backing layer.
CAMetalLayer is a
Core Animation layer that manages a pool of textures for rendering its content. To use
Metal for rendering, we need to use this class as the backing layer for our view by returning it from your view’s layerClass() class method.:
Next, inside the render() function create a new
device and tell metalLayer that it owns it, and also set the pixel format the layer will use. Then, create a
drawable. Notice that we are not using a
currentDrawable that was provided with the
CAMetalLayer provides a nextDrawable for us to use. Finally, create a render pass descriptor. Again, notice that we are not provided with a
Before the end of this episode, let’s look at the MTKView class to see once again why this is the preferred way of using
Metal for rendering content in our apps:
Among the plethora of properties, notice the ones we were interested in particular: device, currentDrawable and currentRenderPassDescriptor. Also worth mentioning, the class provides a protocol for its MTKViewDelegate property. To read more about each of these properties and functions, see the MTKView reference documentation.
The source code is posted on Github as usual.
Until next time!