How to code a MTKView that draws multiple shapes
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
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
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
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
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
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.