如何将 AVCaptureVideoPreviewLayer 旋转 90 度以在 iOS11 中更正它?
Posted
技术标签:
【中文标题】如何将 AVCaptureVideoPreviewLayer 旋转 90 度以在 iOS11 中更正它?【英文标题】:How to rotate a AVCaptureVideoPreviewLayer by 90 degrees to correct it in iOS11? 【发布时间】:2018-03-25 07:04:56 【问题描述】:我有一个AVCaptureVideoPreviewLayer
,它被设置为使用前置摄像头捕捉会话的实时预览。但是,输出旋转了 90 度,我试图让图层与我的应用程序的其余部分对齐,即Landscape
方向。有没有办法通过90 degrees
旋转它以纠正它?
到目前为止,这是我的代码:
override func viewDidLoad()
super.viewDidLoad()
let captureSession = AVCaptureSession()
guard let captureDevice = getDevice(position: .front) else return
guard let input = try? AVCaptureDeviceInput(device: captureDevice) else return
captureSession.addInput(input)
captureSession.startRunning()
let previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
view.layer.addSublayer(previewLayer)
previewLayer.frame = view.frame
previewLayer.videoGravity = .resizeAspectFill
previewLayer.connection?.automaticallyAdjustsVideoMirroring = false
previewLayer.connection?.isVideoMirrored = false
func getDevice(position: AVCaptureDevice.Position) -> AVCaptureDevice?
let devices = AVCaptureDevice.devices() as NSArray;
for de in devices
let deviceConverted = de as! AVCaptureDevice
if(deviceConverted.position == position)
return deviceConverted
return nil
【问题讨论】:
【参考方案1】:您能否将previewLayer
添加到另一个UIView
,然后尝试像这样旋转:
private var captureView: UIView!
override func viewDidLoad()
super.viewDidLoad()
self.captureView = UIView(frame: self.view.bounds)
self.captureView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
self.view.addSubview(captureView)
// ...
captureView.layer.addSublayer(previewLayer)
// ...
self.rotateView(animated: false)
// Rotating captureView based on device orientation
func rotateView(animated: Bool)
var transform: CGAffineTransform?
switch UIDevice.current.orientation
case .portraitUpsideDown:
transform = CGAffineTransform(rotationAngle: CGFloat.pi)
case .landscapeLeft:
transform = CGAffineTransform(rotationAngle: CGFloat.pi / 2)
case .landscapeRight:
transform = CGAffineTransform(rotationAngle: -CGFloat.pi / 2)
default:
break
guard animated else
self.captureView.transform(transform)
return
UIView.animate(withDuration: 0.5, animations: [weak self] in
self?.captureView.transform(transform)
)
【讨论】:
以上是关于如何将 AVCaptureVideoPreviewLayer 旋转 90 度以在 iOS11 中更正它?的主要内容,如果未能解决你的问题,请参考以下文章