How to change the background color of an MTKView in Swift

To change the background color, set isOpaque to false and set the clearColor to a MTLClearColor.

Oscar de la Hera Gomez
Written by Oscar de la Hera Gomez
First published on 10/31/2023 at 23:28
Last Updated on 11/01/2023 at 00:03
<p>Three flowers that represent Swift, Metal and Xcode side by side. Beneath them sits the text "MTKView Background Color."</p>

To change the background color, set isOpaque to false and set the clearColor to a MTLClearColor.

SubscribeDownload Open Source Project

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/background-color branch.

git clone git@github.com:delasign/swift-starter-project.git
View Repository

Step One: Setup the Project

<p>A screenshot of an iPhone showing two shapes drawn in metal. One is filled and the other is outlined with a stroke that we set in code. This proves the functionality works.</p>

Follow the tutorials below to learn how to create a polygons, with a color fill or with a variable line width through shared functionality.

How to structure variables & functionality in shared files in Metal

Step Two: Set the Background Color

<p>A screenshot of Xcode highlighting how we have set the MTKView is isOpaque property to false and its clear color property to an MTKClearColor.</p>

In the MetalUIView+UI.swift file, set the :

  • clearColor property of the MTKView to a MTLClearColor.
  • isOpaque property of the MTKView to false.

Please note without isOpaque set to false, the alpha channel will not work as expected.

Step Three: Test

<p>A screenshot showing an iPhone that demonstrates the the MTKView now has has a clear background. If you do not set the clear color property it will always be black. If you do not set the isOpaque property to false, you will not be able to achieve transparency.</p>

Run the code on a device and confirm that the drawing 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.

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