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

如何阻止Continuity Camera自动校正视频方向?

解决Continuity Camera自动校正视频方向的问题

Continuity Camera默认会根据设备姿态自动调整输出视频方向,导致iPhone朝下对准桌面时视频被强制转为横屏。你可以通过以下步骤禁用这个自动行为,手动控制视频方向:

1. 禁用设备自动方向调整

在配置AVCaptureDevice时,关闭自动方向校正并手动指定固定方向:

guard let captureDevice = AVCaptureDevice.default(.builtInWideAngleCamera, for: .video, position: .back) else {
    return
}

do {
    try captureDevice.lockForConfiguration()
    // 关闭系统自动方向校正
    captureDevice.automaticallyAdjustsVideoOrientation = false
    // 固定为竖屏(可根据需求修改为其他方向)
    captureDevice.videoOrientation = .portrait
    captureDevice.unlockForConfiguration()
} catch {
    print("配置设备失败: \(error.localizedDescription)")
}

2. 同步预览层方向

确保AVCaptureVideoPreviewLayer的视频方向与设备配置一致,避免预览画面异常:

let previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
if let connection = previewLayer.connection, connection.isVideoOrientationSupported {
    connection.videoOrientation = .portrait
}
// 将previewLayer添加到视图层级

3. 同步输出流方向

如果使用AVCaptureVideoDataOutput或AVCapturePhotoOutput处理帧数据,也要同步设置它们的连接方向:

// 以AVCaptureVideoDataOutput为例
let videoOutput = AVCaptureVideoDataOutput()
if let connection = videoOutput.connection(with: .video), connection.isVideoOrientationSupported {
    connection.videoOrientation = .portrait
}
captureSession.addOutput(videoOutput)

4. 可选:自定义姿态响应逻辑

如果需要在用户调整设备姿态时手动控制方向(而非系统自动校正),可以监听设备方向变化并按需更新:

// 注册方向变化通知
NotificationCenter.default.addObserver(
    self,
    selector: #selector(handleDeviceOrientationChange),
    name: UIDevice.orientationDidChangeNotification,
    object: nil
)

@objc private func handleDeviceOrientationChange() {
    guard let captureDevice = captureDevice,
          let previewConnection = previewLayer.connection,
          previewConnection.isVideoOrientationSupported else {
        return
    }
    
    let currentOrientation = UIDevice.current.orientation
    // 仅在设备处于有效方向时更新,忽略朝下/朝上的情况
    switch currentOrientation {
    case .portrait:
        previewConnection.videoOrientation = .portrait
    case .landscapeLeft:
        previewConnection.videoOrientation = .landscapeLeft
    case .landscapeRight:
        previewConnection.videoOrientation = .landscapeRight
    case .portraitUpsideDown:
        previewConnection.videoOrientation = .portraitUpsideDown
    default:
        // 设备朝下/朝上时,保持当前方向不变
        break
    }
}

注意事项

  • 修改设备配置前必须调用lockForConfiguration(),修改完成后调用unlockForConfiguration(),避免线程冲突。
  • 部分旧款iPhone可能对automaticallyAdjustsVideoOrientation的支持有限,建议多机型测试。
  • 若应用需要适配不同场景,可根据实际需求调整固定方向或自定义方向映射逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 17:42:07