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

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

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

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.