我基本上是在回答这个问题AVCaptureVideoPreviewLayer orientation - need landscape,除了在Swift。
我的目标是iOS 8,而AVCaptureVideoPreviewLayer似乎没有setVideoOrientation功能。
我应该如何检测方向已更改,并正确旋转AVCaptureVideoPreviewLayer?
检测并应用于viewWillLayoutSubviews
。
这是如何做:
override func viewWillLayoutSubviews() {
let orientation: UIDeviceOrientation = UIDevice.currentDevice().orientation
print(orientation)
switch (orientation) {
case .Portrait:
previewLayer?.connection.videoOrientation = .Portrait
case .LandscapeRight:
previewLayer?.connection.videoOrientation = .LandscapeLeft
case .LandscapeLeft:
previewLayer?.connection.videoOrientation = .LandscapeRight
default:
previewLayer?.connection.videoOrientation = .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
}
}
对我来说,当我向左或向右旋转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
}
}
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;
}
}
Swift 4中的另一个解决方案是使用Notification。
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小时,因为在这种情况下,方法不会被截获:))。