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.

Oscar de la Hera Gomez
Written by Oscar de la Hera Gomez
First published on 10/03/2023 at 15:47
Last Updated on 10/04/2023 at 14:40
<p>Three flowers that represent Swift, Metal and XCode with the text "Primitive Line in Metal."</p>

A step by step tutorial on implementing a MTKView in a UIView that draws a shape with an outline.

SubscribeCheck out our Apple Metal Resources Guide

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
View RepositoryHow to create a SwiftLint enabled Swift XCode Project

Step One: Setup the MTKView

<p>A screenshot of an iPhone showing a black background with a red triangle that was produced with metal.</p>

Follow the tutorial below to setup a MTKView within a UIView that shows a triangle.

How to use Metal with a UIView in Swift

Step Two: Update the Vertices

<p>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.</p>

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

<p>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.</p>

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

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

Update the SampleMetalShader.metal file to the code below.

Step Five: Test

<p>A screenshot of Xcode showing a triangle with an outline.</p>

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.

Search our Blog

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.
SubscribeContact UsVisit our BlogView our ServicesView our Work

Partner with us

We would love to get to know you and see how we can help your organization with its goals and needs.
Let's Talk

Stay Informed

Get occasional updates about our company, research, and product launches.
Subscribe