我基本上是在寻找这个问题的答案:AVCaptureVideoPreviewLayer方向 - 需要横屏,但是用Swift。
我正在针对iOS 8进行开发,但是AVCaptureVideoPreviewLayer似乎没有setVideoOrientation函数。
我应该如何检测方向已更改,并适当旋转AVCaptureVideoPreviewLayer?
我基本上是在寻找这个问题的答案:AVCaptureVideoPreviewLayer方向 - 需要横屏,但是用Swift。
我正在针对iOS 8进行开发,但是AVCaptureVideoPreviewLayer似乎没有setVideoOrientation函数。
我应该如何检测方向已更改,并适当旋转AVCaptureVideoPreviewLayer?
在viewWillLayoutSubviews
中检测并应用它,或者如果您正在使用layoutSubviews
的UIView子类,则可以这样做。
操作方法如下:
override func viewWillLayoutSubviews() {
let orientation: UIDeviceOrientation = UIDevice.current.orientation
previewLayer.connection?.videoOrientation = {
switch (orientation) {
case .portrait:
return .portrait
case .landscapeRight:
return .landscapeLeft
case .landscapeLeft:
return .landscapeRight
default:
return .portrait
}
}()
}
更新至Swift 3
override func viewWillLayoutSubviews() {
let orientation: UIDeviceOrientation = UIDevice.current.orientation
print(orientation)
switch (orientation) {
case .portrait:
videoPreviewLayer?.connection.videoOrientation = .portrait
case .landscapeRight:
videoPreviewLayer?.connection.videoOrientation = .landscapeLeft
case .landscapeLeft:
videoPreviewLayer?.connection.videoOrientation = .landscapeRight
case .portraitUpsideDown:
videoPreviewLayer?.connection.videoOrientation = .portraitUpsideDown
default:
videoPreviewLayer?.connection.videoOrientation = .portraitUpsideDown
}
}
在ViewController中的Xamarin解决方案;
public override void ViewWillLayoutSubviews()
{
base.ViewWillLayoutSubviews();
var videoPreviewLayerConnection = PreviewView.VideoPreviewLayer.Connection;
if (videoPreviewLayerConnection != null)
{
var deviceOrientation = UIDevice.CurrentDevice.Orientation;
if (!deviceOrientation.IsPortrait() && !deviceOrientation.IsLandscape())
return;
var newVideoOrientation = VideoOrientationFor(deviceOrientation);
var oldSize = View.Frame.Size;
var oldVideoOrientation = videoPreviewLayerConnection.VideoOrientation;
videoPreviewLayerConnection.VideoOrientation = newVideoOrientation;
}
}
对我来说,我需要在我将iPad向左或向右旋转时改变方向,帮助我的解决方案是:
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
let orientation = UIDevice.current.orientation
switch (orientation) {
case .portrait:
videoPreviewLayer?.connection.videoOrientation = .portrait
case .landscapeLeft:
videoPreviewLayer?.connection.videoOrientation = .landscapeRight
case .landscapeRight:
videoPreviewLayer?.connection.videoOrientation = .landscapeLeft
default:
videoPreviewLayer?.connection.videoOrientation = .portrait
}
}
在 Swift 4 中,另一个解决方案是使用通知。
NotificationCenter.default.addObserver(self,
selector: #selector(detected),
name:
UIDevice.orientationDidChangeNotification,object: nil)
在选择器函数中,您可以检查方向:
let orientation: UIDeviceOrientation = UIDevice.current.orientation
switch orientation {
case .portrait:
stuff()
case .landscapeLeft:
stuffOther()
case .landscapeRight
stuffOther()
default:
stuffOther()
}
记得在不需要时删除观察者。
非常重要:你的物理iPhone不能有旋转锁定(我因为这个浪费了2个小时,因为在这种情况下,方法不会被拦截 :))。