How to change the background color of an MTKView in Swift

Oscar de la Hera Gomez
Three flowers that represent Swift, Metal and Xcode side by side. Beneath them sits the text "MTKView Background Color."

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

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

Step One: Setup the Project

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.

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

Step Two: Set the Background Color

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

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

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.

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.

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