我已将我的应用中的固定设备方向限制为仅限肖像。然而就像Instagram一样,我有一个相机功能,我需要在swift中获得当前的方向,但方向始终显示为肖像。有没有办法使用陀螺仪手动获取方向?
答案 0 :(得分:1)
即使您不支持自动轮换,UIDevice也可以告诉您方向。我用它来只处理一个视图控制器中的旋转:
override func viewDidLoad() {
super.viewDidLoad()
UIDevice.current.beginGeneratingDeviceOrientationNotifications()
NotificationCenter.default.addObserver(self, selector: #selector(orientationChanged), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)
}
deinit {
UIDevice.current.endGeneratingDeviceOrientationNotifications()
NotificationCenter.default.removeObserver(self)
}
@objc private func orientationChanged(_ notification: Foundation.Notification) {
currentOrientation = UIDevice.current.orientation
}
答案 1 :(得分:0)
在Swift 2.3中,您可以使用以下代码设置AVCaptureDeviceInput的方向(或替换为您自己的功能)。
我在https://github.com/ytakzk/Fusuma - >中使用了此代码FSCameraView.swift
import CoreMotion
//var videoInput: AVCaptureDeviceInput?
let motionManager = CMMotionManager()
if motionManager.gyroAvailable {
motionManager.deviceMotionUpdateInterval = 0.2;
motionManager.startDeviceMotionUpdates()
motionManager.gyroUpdateInterval = 1
motionManager.startDeviceMotionUpdatesToQueue(NSOperationQueue.currentQueue()!) {
(data: CMDeviceMotion?, error:NSError?) in
if let videoConnection = self.imageOutput?.connectionWithMediaType(AVMediaTypeVideo) {
if (data?.gravity.x)! > -0.6 && (data?.gravity.x)! < 0.6 {
if (data?.gravity.y)! < 0.4 {
videoConnection.videoOrientation = .Portrait
} else {
videoConnection.videoOrientation = .PortraitUpsideDown
}
} else {
if (data?.gravity.x)! < 0 {
videoConnection.videoOrientation = .LandscapeRight
} else {
videoConnection.videoOrientation = .LandscapeLeft
}
}
}
//print(data?.gravity.x)
//print(data?.gravity.y)
//print(data?.gravity.z)
}
}