Swift陀螺仪

Swift Gyroscope

我正在构建一个需要拍摄水平照片的应用程序。我想用陀螺仪确保拍照时phone水平

我已经获得了陀螺仪更新(即使设备没有移动,它也会逐渐增加)但我似乎无法找到如何获得初始陀螺仪坐标。

如何获取陀螺仪的初始值?

这是我的代码的精简版

import UIKit
import CoreMotion

class SizingFlowFrontPhotoViewController: UIViewController, AVCapturePhotoCaptureDelegate {


    var gyroX:Double = 0.0
    var gyroY:Double = 0.0
    var gyroZ:Double = 0.0

    var motionManager = CMMotionManager()

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)


        motionManager.gyroUpdateInterval = 0.2
        motionManager.startGyroUpdates(to: OperationQueue.current!) { (data, error) in
            if let myData = data {
                // x = rotate it on sim card (front flip/back flip)
                // y = rotate it on charger (twister spin)
                // z = rotate it on tilt (landscape vs portrait)
                self.gyroX += myData.rotationRate.x
                self.gyroY += myData.rotationRate.y
                self.gyroZ += myData.rotationRate.z
                print("gyroX: \(self.gyroX) - gyroY: \(self.gyroY) - gyroZ: \(self.gyroZ)")
            }
        }

    }

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        motionManager.stopGyroUpdates()
    }


}

我发现我用错了设备。

我应该一直在使用 deviceMotion。像这样。

motionManager.deviceMotionUpdateInterval = 0.05
        motionManager.startDeviceMotionUpdates(to: OperationQueue.current!) { (data, error) in
            if let myData = data{
                self.mPitch = myData.attitude.pitch * 180 / Double.pi
                self.mRoll = myData.attitude.roll * 180 / Double.pi
                self.mYaw = myData.attitude.yaw * 180 / Double.pi
                self.updateGyroBarPosition()
            }
        }