How to use multiple shaders to draw multiple shapes within a MTKView

Oscar de la Hera Gomez
Three flowers that represent Swift, Metal and Xcode with the text "Multiple Shaders" beneath it.

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 an outlined Pentagon above a filled circle. Both outlined and filled shape show a gradient that covers all the RGB colors available.

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

A screenshot of Xcode showing the InverseColorWheelMetalShader.metal file that we created to show how you can use multiple shaders.

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

A screenshot of the MetalUIView+UI.swift file highlighting how we removed the code that is used to declare the metal shader.

In the MetalUIView+UI.swift file, remove the code that sets the vertex and fragment shader functions.

Step Four: Update the Metal Delegate

A screenshot of Xcode showing the updated MetalUIView+MetalDelegate.swift file. Code available below.

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

A screenshot of an iPhone that shows a pentagon and a circle each with different colors. This demonstrates that different shaders are being used.

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.

Any Questions?

We are actively looking for feedback on how to improve this resource. Please send us a note to inquiries@delasign.com with any thoughts or feedback you may have.
delasign logo

Book a Free Consultation.

An icon of an email.

Click here to email us.

Fill in the details below to book a free consultation or to let us know about something else. Whatever it is, we are here to help.

How can we help you ?

Contact Details