iOS应用相机方向切换异常问题求助
解决iOS相机横屏画面异常的问题
你的问题核心出在视频旋转角度设置错误和图层适配逻辑不完善上,以下是具体修复方案:
问题分析
- 你给
landscapeLeft和landscapeRight设置的180/-180角度完全错误,这两个方向对应的正确旋转角度应为90°和-90°(或270°)。 - 直接修改
previewLayer.frame未结合过渡动画,会导致画面跳变;同时未设置图层内容填充规则,无法适配屏幕比例。 - 使用
UIScreen.main.bounds不如直接使用控制器view的bounds,更贴合实际布局场景。
修复后的代码
override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) { super.willTransition(to: newCollection, with: coordinator) // 用控制器view的bounds作为图层尺寸,适配布局 let targetBounds = view.bounds coordinator.animate(alongsideTransition: { _ in // 设置图层填充规则,保证画面填满屏幕且比例正确 self.previewLayer.contentsGravity = .resizeAspectFill self.previewLayer.frame = targetBounds // 根据设备方向设置正确的视频旋转角度 switch UIDevice.current.orientation { case .portraitUpsideDown: self.previewLayer.connection?.videoRotationAngle = 180 case .landscapeLeft: // Home键在右侧,对应顺时针转90° self.previewLayer.connection?.videoRotationAngle = 90 case .landscapeRight: // Home键在左侧,对应逆时针转90° self.previewLayer.connection?.videoRotationAngle = -90 case .portrait: self.previewLayer.connection?.videoRotationAngle = 0 default: break } }, completion: nil) }
额外注意事项
- 确保相机会话(
AVCaptureSession)支持当前方向的分辨率,可手动设置sessionPreset为.high或.hd1920x1080这类适配性较好的选项。 - 若控制器支持自动旋转,需在
supportedInterfaceOrientations中声明允许的方向,避免旋转逻辑冲突。 - 若存在安全区域,可将
targetBounds替换为view.safeAreaLayoutGuide.layoutFrame,避免画面被刘海、底部条遮挡。
内容的提问来源于stack exchange,提问作者Prathyush Yeturi
相关产品推荐
相关产品推荐

