How to draw a polygon in Metal
A step by step tutorial on drawing a shape (i.e. a triangle, square, pentagon or circle), either 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/polygon branch.
git clone git@github.com:delasign/swift-starter-project.git
Step One: Setup the MTKView
Follow the tutorial below to setup a MTKView within a UIView that shows a triangle.
Step Two: Create the Uniforms
Under Models/Metal create a new file called PolygonUniforms.swift and paste in the code below.
This struct represents the data structure that will be passed from the UIView to the Metal shader.
Step Three: Update the Metal View UI File
Remove the vertices and vertex buffer code from the MetalUIView+UI.swift file.
We do not need this code as in this tutorial we will be defining the position of the vertices in the shader file.
Subsequently, change the sample_vertex_main and sample_fragment_main to polygon_vertex_main and polygon_fragment_main.
This is updated in Step Five.
Step Four: Update the Metal View Delegate File
Update the MetalUIView+MetalDelegate.swift file to the code below.
This code makes use of buffers that are passed to the metal shader and defines the number of vertices in the drawPrimitives function.
Step Five: Update the Metal Shader
Update the metal shader to the code found below.
This code makes use of the Uniforms passed in on Step Four and applies the aspect ratio to make sure that the circle is drawn correctly.
Please note that we renamed SampleMetalShader.metal to PolygonMetalShader.metal, and have also renamed the vertex and fragment functions.
For more information on how all of this works, please consult the article linked below.
Step Six: Test
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.