You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SwiftUI中如何将SceneView的背景设置为透明?

SwiftUI SceneView 透明背景实现方案

要实现SceneView背景透明,需要同时配置SCNScene场景属性和底层SCNView渲染参数,单改其中任意一项都会出现黑色背景问题。

核心修改步骤

  • 加载3D场景资源后,将场景背景内容设置为透明色
  • 关闭SceneView底层渲染视图的不透明标识
  • 确保渲染配置不额外生成默认背景层

可直接运行的修改后代码

private var scene: SCNScene? {
    guard let scene = SCNScene(named: "Globe.scnassets/sphere.scn") else { return nil }
    // 配置场景本身为透明背景
    scene.background.contents = UIColor.clear
    return scene
}
    
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]
    )
    .background(Color.clear)
    .onAppear {
        // 兜底修改底层SCNView属性,解决系统SceneView未暴露透明配置的问题
        DispatchQueue.main.async {
            guard let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene,
                  let rootView = windowScene.windows.first?.rootViewController?.view else {
                return
            }
            findAndConfigSCNView(in: rootView)
        }
    }
}

// 递归查找子视图中的SCNView并配置透明
private func findAndConfigSCNView(in view: UIView) {
    if let scnView = view as? SCNView {
        scnView.backgroundColor = .clear
        scnView.isOpaque = false
        return
    }
    view.subviews.forEach { findAndConfigSCNView(in: $0) }
}

适配说明

  • iOS 16及以上系统可省略递归查找SCNView的逻辑,直接给SceneView追加修饰符.containerBackground(.clear, for: .sceneView)即可
  • 若3D模型资源本身自带不透明底图,需要先在3D编辑工具中删除底图节点,否则无法透出下层视图
  • 若开启了HDR或屏幕空间反射效果,需额外将scene.wantsScreenSpaceReflection属性设为false,避免反射层生成不透明遮罩

内容的提问来源于stack exchange,提问作者Mc.Lover

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.01 04:57:54