How to draw a stroke on a primitive in Metal
A step by step tutorial on implementing a MTKView in a UIView that draws a shape with an outline.
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/triangle-stroke 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: Update the Vertices
In the MetalUIView+UI.swift file, update the vertices to include the first vertex at the end of the array.
This is required to close the loop within the triangle and applies to any other shape you wish to outline.
Step Three: Update the Delegate
In the MetalUIView+MetalDelegate.swift file, update the vertex count to 4 and set the drawPrimtives type to .lineStrip.
This number should be 1 more than whatever count your primitive had before adding an outline.
Step Four: Update the Metal Shader
Update the SampleMetalShader.metal file to the code below.
Step Five: Test
Run the code on a device and confirm that you see a triangle.
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.