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

RealityKit+SwiftUI中前置摄像头画面镜像致AR检测失败,如何翻转图像?

前置摄像头画面镜像导致AR图像检测失败的解决方法

我在SwiftUI结合RealityKit开发时,需要切换前后摄像头,但使用前置摄像头时,捕获的画面出现镜像问题,导致应用无法检测到Assets中「AR Resources」目录下添加的图像。

原始切换摄像头函数代码:

func switchCamera() {
    
    print("DEBUGG: switchCamera on Model")
    guard var newConfig = arView.session.configuration else {
        return
    }
    
    switch newConfig {
    case is ARWorldTrackingConfiguration:
        newConfig = ARFaceTrackingConfiguration()
    case is ARFaceTrackingConfiguration:
        newConfig = ARWorldTrackingConfiguration()
    default:
        newConfig = ARWorldTrackingConfiguration()
    }
    arView.session.run(newConfig)
}

捕获的镜像画面:
前置摄像头镜像画面


解决方案

通过为AR视图指定变换属性,仅需两行代码即可修复镜像问题:

  • 前置摄像头使用:arView.transform = CGAffineTransform(scaleX: -1, y: 1)
  • 后置摄像头重置为默认:arView.transform = CGAffineTransform(scaleX: 1, y: 1)

修改后的switchCamera()函数:

func switchCamera() {
    
    print("DEBUGG: switchCamera on Model")
    guard var newConfig = arView.session.configuration else {
        return
    }
    
    switch newConfig {
    case is ARWorldTrackingConfiguration:
        newConfig = ARFaceTrackingConfiguration()
        arView.transform = CGAffineTransform(scaleX: -1, y: 1) // 添加镜像翻转
    case is ARFaceTrackingConfiguration:
        newConfig = ARWorldTrackingConfiguration()
        arView.transform = CGAffineTransform(scaleX: 1, y: 1) // 恢复默认
    default:
        newConfig = ARWorldTrackingConfiguration()
    }
    arView.session.run(newConfig)
}

修复后的效果(前后摄像头均正常):
修复后的摄像头画面

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 23:05:25