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

iOS 11中AVCapturePhotoOutput方向无法修改问题求助

解决AVFoundation捕获照片方向异常的问题

我太懂你这种闹心的感觉了——预览界面明明显示正常,拍出来的CMSampleBuffer却变成左横屏,调photoOutputConnection.videoOrientation还没效果,这坑我之前也踩过!咱们一步步来把问题解决掉:

问题核心原因

你之前的代码只做了方向支持性检查,但没有把设备的实际物理朝向同步到捕获输出连接上,而且设置时机也不对——方向配置必须在触发拍照的瞬间完成,不能只在会话初始化时设置一次。

正确的解决方案

1. 先写个工具方法获取当前设备的正确视频方向

注意UIInterfaceOrientation和AVCaptureVideoOrientation的映射是反向的,这是很多人踩的坑:

func getCurrentCaptureOrientation() -> AVCaptureVideoOrientation {
    let interfaceOrientation = UIApplication.shared.statusBarOrientation
    switch interfaceOrientation {
    case .portrait:
        return .portrait
    case .portraitUpsideDown:
        return .portraitUpsideDown
    case .landscapeLeft:
        return .landscapeRight // 设备左横屏对应捕获的右横屏
    case .landscapeRight:
        return .landscapeLeft // 设备右横屏对应捕获的左横屏
    default:
        return .portrait
    }
}

2. 在拍照前立刻设置输出连接的方向

别只在会话初始化时检查,要在调用capturePhoto(with:delegate:)的前一刻配置:

// 比如你的拍照按钮点击方法
func captureButtonTapped() {
    guard let photoOutputConnection = capturePhotoOutput.connection(with: .video) else { return }
    
    if photoOutputConnection.isVideoOrientationSupported {
        let targetOrientation = getCurrentCaptureOrientation()
        photoOutputConnection.videoOrientation = targetOrientation
        print("已同步视频方向为: \(targetOrientation)")
    }
    
    // 配置照片参数
    let photoSettings = AVCapturePhotoSettings()
    photoSettings.isHighResolutionPhotoEnabled = capturePhotoOutput.isHighResolutionCaptureEnabled
    
    // 触发捕获
    capturePhotoOutput.capturePhoto(with: photoSettings, delegate: self)
}

3. 额外:同步预览层的方向(可选但建议)

如果你的预览层是手动设置的,也同步一下方向,避免预览和最终照片的方向感知不一致:

previewLayer.connection?.videoOrientation = getCurrentCaptureOrientation()

为什么之前的代码没效果?

你之前的代码只是打印了当前连接的默认方向,但没有主动将其设置为设备的实际朝向;而且如果是在会话初始化时设置,之后设备旋转了,连接的方向不会自动更新——必须每次拍照前重新同步,才能保证捕获的方向正确。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 03:54:01