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

RealityKit双ARView问题:.nonAR模式视图显示相机画面且失真如何解决?

问题分析与解决方案

你的问题出在三个核心点:nonAR模式的ARView错误启动了AR会话、视图背景透明导致透出下层相机画面,以及相机参数未适配视图宽高比引发失真。

解决步骤:

  1. 关闭nonAR视图的AR会话自动配置
    创建arView2时,将automaticallyConfigureSession设为false——nonAR模式仅用于纯3D渲染,不需要AR会话(即不需要相机输入),自动配置会错误关联AR相机流:

    let arView2 = ARView(frame: CGRect(x:50,y:300,width: 200,height:200),
                         cameraMode: .nonAR,
                         automaticallyConfigureSession: false)
    
  2. 设置nonAR视图的黑色背景
    默认情况下nonAR模式的ARView背景是透明的,会透出下层全屏ARView的相机画面,手动设置背景色为黑色即可:

    arView2.environment.background = .color(.black)
    
  3. 适配相机参数避免画面失真
    nonAR模式下默认相机的投影矩阵未匹配视图宽高比,手动添加一个适配的透视相机:

    // 创建并配置透视相机
    let camera = PerspectiveCamera()
    camera.position = [0, 0, 0]
    camera.look(at: [0, 0, -1]) // 固定看向物体方向
    camera.fieldOfView = 60 // 设置合理视角范围
    camera.aspectRatio = arView2.bounds.width / arView2.bounds.height // 匹配视图宽高比
    arView2.scene.addAnchor(camera)
    
  4. (可选)优化视图缩放适配
    为避免视图尺寸变化时失真,添加 autoresizingMask:

    arView2.autoresizingMask = [.flexibleWidth, .flexibleHeight]
    

修改后的完整代码:

let arView = ARView(frame: self.view.frame,
                    cameraMode: .ar,
                    automaticallyConfigureSession: true)
view.addSubview(arView)

let newAnchor = AnchorEntity(world: [0, 0, -1])
let newBox = ModelEntity(mesh: .generateBox(size: 0.5))
newAnchor.addChild(newBox)
arView.scene.anchors.append(newAnchor)


let arView2 = ARView(frame: CGRect(x:50,y:300,width: 200,height:200),
                     cameraMode: .nonAR,
                     automaticallyConfigureSession: false)
arView2.environment.background = .color(.black)
arView2.autoresizingMask = [.flexibleWidth, .flexibleHeight]
view.addSubview(arView2)

// 配置nonAR视图的相机
let camera = PerspectiveCamera()
camera.position = [0, 0, 0]
camera.look(at: [0, 0, -1])
camera.fieldOfView = 60
camera.aspectRatio = arView2.bounds.width / arView2.bounds.height
arView2.scene.addAnchor(camera)

let newAnchor2 = AnchorEntity(world: [0, 0,-1])
let newBox2 = ModelEntity(mesh: .generateBox(size: 0.5))
newAnchor2.addChild(newBox2)
arView2.scene.anchors.append(newAnchor2)

这样修改后,arView2会显示黑色背景下的3D盒子,且画面不会失真。

内容的提问来源于stack exchange,提问作者Gogo123

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 13:36:31