How to use multiple shaders to draw multiple shapes within a MTKView
A step by step tutorial on drawing shapes that use different shaders in a UIView using Metal.
We recommend that you clone our Open Source Swift Starter Project, checking out the main branch and carrying out the steps below. The changes can be found on the tutorial/metal/multiple-shaders branch.
git clone git@github.com:delasign/swift-starter-project.git
Step One: Setup the project
A screenshot of an iPhone showing a view that has drawn a pentagon (outlined) and a circle (filled) using metal.
Follow the tutorial below to setup a MTKView within a UIView that draws multiple shapes.
Step Two: Write the new Shader
In the Xcode project, create and write a new Metal shader.
We suggest that you place this under the UI/Shaders folder.
Step Three: Remove the Shader Declaration Code
In the MetalUIView+UI.swift file, remove the code that sets the vertex and fragment shader functions.
Step Four: Update the Metal Delegate
Update the MetalUIView+MetalDelegate.swift file to the code found below.
The key changes in this file are:
- The inclusion of a vertexShaderFunction and fragmentShaderFunction argument in the drawPolygon function.
- The functionality that uses these arguments to set the pipeline state of the device.
Step Five: Test
Run the code on a device and confirm that multiple shapes appear.
Each of these shapes should have different colors, depending on the shader that you applied in Step Four.
Looking to learn more about things you can do with Swift, Metal and XCode ?
Search our blog to find educational content on learning how to use Swift, Metal and XCode.