iOS 获取摄像头当前方向
在做二维码扫描和直播获取视频流的过程中,可能会用到
AVCaptureDevice
AVCaptureVideoPreviewLayer
AVCaptureSession
这几个参数,其中
1、定义显示layer
var preview:AVCaptureVideoPreviewLayer! = nil
2、获取摄像头方向
self.preview = AVCaptureVideoPreviewLayer(session: self.session) self.preview.videoGravity = AVLayerVideoGravityResizeAspectFill self.preview.connection.videoOrientation = self.getDeviceDirection()
重点就是这里getDeviceDirection方法,这里我的做法就是根据当前状态栏方向判断摄像头方向。
代码实现:
/// 获取当前摄像头方向 /// /// - Returns: <#return value description#> func getDeviceDirection() -> AVCaptureVideoOrientation{ switch UIApplication.shared.statusBarOrientation { case .landscapeLeft: return AVCaptureVideoOrientation.landscapeLeft case .landscapeRight: return AVCaptureVideoOrientation.landscapeRight case .portrait: return AVCaptureVideoOrientation.portrait case .portraitUpsideDown: return AVCaptureVideoOrientation.portraitUpsideDown default: return AVCaptureVideoOrientation.landscapeRight } }