4

Does anybody knows how to change the color of the background of a SceneView object? I'm trying by just placing the background attribute to the SceneView, but it doesn't change it, still with a default background.In this case I wanted to the background be green, but it's keeps gray/white

import SwiftUI
import SceneKit

struct ContentView: View {
    var body: some View {
    
        ZStack{
            Color.red
            SceneView(
                scene: SCNScene(named: "Earth.scn"),
                options: [.autoenablesDefaultLighting,.allowsCameraControl]
            )
            .frame(width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height/2, alignment: .center)
            .background(Color.green)
            .border(Color.blue, width: 3)
        
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

1 Answers1

9

The gray that you are seeing is from SCNScene's background property. You need to set this to UIColor.green.

struct ContentView: View {
    var body: some View {
        
        ZStack{
            Color.red
            SceneView(
                scene: {
                    let scene = SCNScene(named: "Earth.scn")!
                    scene.background.contents = UIColor.green /// here!
                    return scene
                }(),
                options: [.autoenablesDefaultLighting, .allowsCameraControl]
            )
            .frame(width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height/2, alignment: .center)
            .border(Color.blue, width: 3)
            
        }
    }
}

Result:

green background in SceneView
aheze
  • 24,434
  • 8
  • 68
  • 125
  • 3
    How can I make it transparent? I tried UIColor.clear but it makes it white instead. – Susca Bogdan Nov 29 '21 at 18:55
  • 1
    @SuscaBogdan `SceneView` in SwiftUI doesn't support this yet, but this might help: https://stackoverflow.com/q/67557700/14351818 – aheze Nov 29 '21 at 19:24
  • It seems that it doesn't differentiate colors from xcassets i.e. dark light and you need to set correct UIColor directly both for dark and light mode :( – Michał Ziobro Jun 03 '22 at 11:05