Mc.Lover
Mc.Lover

Reputation: 4994

How to make SceneView's background clear in SwiftUI?

I am showing a 3D object in SwiftUI, and I have a problem with making the object's background clear. I have searched and did not find any solution. Is there any solution for this?

private var scene: SCNScene? {
    SCNScene(named: "Globe.scnassets/sphere.scn")
}
    
private var cameraNode: SCNNode? {
    let cameraNode = SCNNode()
    cameraNode.camera = SCNCamera()
    cameraNode.position = SCNVector3(x: 0, y: 0, z: 5)
    return cameraNode
}

var body: some View {
    SceneView(scene: scene,
        pointOfView: cameraNode,
            options: [.allowsCameraControl, .autoenablesDefaultLighting])
}

Upvotes: 3

Views: 883

Answers (2)

Andy Jazz
Andy Jazz

Reputation: 58093

There are, at least, 3 ways to programmatically change a BG in SwiftUI's SceneView.

Default white background

enter image description here


Changing SCNScene's background color

enter image description here

import SwiftUI
import SceneKit

struct ContentView: View {
    
    var scene = SCNScene(named: "model.usdz")
    var options: SceneView.Options = [.autoenablesDefaultLighting,
                                      .allowsCameraControl ]

    var body: some View {
        ZStack {
            SceneView(scene: scene, options: options)
                .ignoresSafeArea()
            let _ = scene?.background.contents = UIColor.black
        }
    }
}


Using textured double-sided SCNGeometry

enter image description here

struct ContentView: View {
    
    var scene = SCNScene(named: "model.usdz")
    var options: SceneView.Options = [.autoenablesDefaultLighting,
                                      .allowsCameraControl ]
    let node = SCNNode(geometry: SCNSphere(radius: 500.0))
    let img = UIImage(named: "image.jpg")

    var body: some View {
        ZStack {
            let _ = node.geometry?.firstMaterial?.diffuse.contents = img
            let _ = node.geometry?.firstMaterial?.isDoubleSided = true
            let _ = scene?.rootNode.addChildNode(node)

            SceneView(scene: scene, options: options)
                .ignoresSafeArea()
        }
    }
}


Using Procedural Sky Box Texture

You can use MDLSkyCubeTexture as background and lightingEnvironment.

Upvotes: 2

Mc.Lover
Mc.Lover

Reputation: 4994

I have found a solution via SceneKit editor, if you want to show an image as background, you can manually do it by going to:

Scene Inspector -> Background and lighting -> Background 

and set the image as background: enter image description here

Upvotes: 1

Related Questions