How to use color interpolation in a Metal shader

Oscar de la Hera Gomez
Three flowers that represent Swift, Metal and XCode side by side. Beneath them sits the text "Color Interpolation."

A step by step tutorial on drawing a filled or outlined shape that interpolates color values between vertices 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/interpolation branch.

git clone git@github.com:delasign/swift-starter-project.git

A triangle that has different colors on its edges (i.e. vertices). The diagram shows how the triangle calculates the colors within the triangle depending on the color of the vertices.

The tutorial outlined below supplies a position and color for each vertex, and the render pipeline uses that data to render the triangle, interpolating color values between the colors specified for the triangle’s vertices.

This behavior is considered out-of-the-box and automatic. To learn more consult the guide below.

Step One: Setup the MTKView

A screenshot of an iPhone showing a black background with a red triangle that was produced with metal.

Follow the tutorial below to setup a MTKView within a UIView that shows a polygon.

Step Two: Update the Metal Shader

A screenshot of Xcode showing the updated metal shader. Code is available below.

Update the metal shader to the code found below.

This metal shader:

  • Determine the color based on the angular position of the vertex to create a color wheel.
  • Passes data from the swift file to the metal shader using a methodology explained in a link below.
  • Passes data from the vertex function to the fragment function using a methodology explained in a link below.

Please note that we renamed the Metal shader to ColorWheelPolygonMetalShader.metal.

Step Three: Test

A screenshot of an iPhone showing a circle with all the RGB colors that are available.

Run the code on a device and confirm that the shader works as expected.

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