How to draw a stroke on a primitive in Metal

Oscar de la Hera Gomez
Three flowers that represent Swift, Metal and XCode with the text "Primitive Line 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

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 triangle.

Step Two: Update the Vertices

A screenshot of Xcode showing the updated MetalUIView+UI.swift file. Highlighted is the location of the file and where we have updated 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

A screenshot of Xcode showing the MetalUIView+MetalDelegate.swift file. Highlighted is the location of the file and the change that we have made to the primitive type and the vertex count.

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

A screenshot of Xcode showing the update to the metal shader. The code is available below.

Update the SampleMetalShader.metal file to the code below.

Step Five: Test

A screenshot of Xcode showing a triangle with an outline.

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.

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