How to code a MTKView that draws multiple shapes

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

A step by step tutorial on drawing multiple shapes, filled or outlined, 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-shapes branch.

Step One: Setup the MTKView

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

Follow the tutorial below to setup a MTKView within a UIView that draws a polygon which features color interpolation.

Step Two: Update the Uniforms struct

A screenshot of Xcode showing the PolygonUniforms struct with the updated dataset.

Add the origin to the PolygonUniforms struct as a SIMD2<Float>.

SIMD2<Float> is the equivalent of the float2 in metal.

Step Three: Update the Delegate

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

Update the MetalUIView+MetalDelegate.swift file to the code below.

The important changes here are:

  • We have made the draw polygon functionality its own function.
  • From within the draw function, we call the draw polygon function multiple times to draw multiple shapes.

Please note that the current methodology uses a single shader.

Step Four: Update the Metal Shader

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

Update the metal shader to the code below.

The key addition here is the addition of the origin coordinate and how the code is adapted to implement the origin coordinate.

Step Four: Test

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.

Run the code on a device and confirm that multiple shapes appear.

As demonstrated above, the code is expected to let you draw both outlined shapes and filled shapes within the same draw function.

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