尝试根据设备的角度旋转图像

Trying to rotate an image according to the angle of the device

我正在尝试根据设备所处的角度旋转图像,但是当我执行我的代码时,图像没有任何反应。这是我的代码:

import UIKit

导入 CoreMotion

 class ViewController: UIViewController {

    @IBOutlet weak var imageView: UIImageView!

    let manager = CMMotionManager()
    let queue = OperationQueue()

    override func viewDidLoad() {
        super.viewDidLoad()
        manager.deviceMotionUpdateInterval = 0.01

        if manager.isDeviceMotionAvailable {

            manager.startDeviceMotionUpdates(to: queue) {
                [weak self] (data: CMDeviceMotion?, error: Error?) in
                    if let gravity = data?.gravity {
                        let rotation = atan2(gravity.x, gravity.y) - M_PI
                        self?.imageView.transform = CGAffineTransform(rotationAngle: CGFloat(rotation))

                    }
            }
        }
        manager.startDeviceMotionUpdates()
    }
}

问题是 if let data = manager.deviceMotion 永远不会运行。我没有收到任何错误,想知道问题出在哪里。感谢任何帮助。

引用运动管理器的文档:

Device motion. Call the startDeviceMotionUpdates(using:) or startDeviceMotionUpdates() method to begin updates and periodically access CMDeviceMotion objects by reading the deviceMotion property. The startDeviceMotionUpdates(using:) method (new in iOS 5.0) lets you specify a reference frame to be used for the attitude estimates.

您需要在 deviceMotion 属性 生效之前开始动态更新。

编辑:

关于您发布的新代码:

您是否单步执行代码以查看发生了什么? manager.isDeviceMotionAvailable 是否为真?你的块被调用了吗?

请注意,您将 OperationQueue 传递给对 manager.startDeviceMotionUpdates 的调用,因此您传入的块将在后台线程上调用。因此,您需要向主线程发送 UI 更新:

manager.startDeviceMotionUpdates(to: queue) {
  [weak self] (data: CMDeviceMotion?, error: Error?) in
  if let gravity = data?.gravity {
    let rotation = atan2(gravity.x, gravity.y) - M_PI
    //Change the image view's transform from the main thread.
    DispatchQueue.main.async() {
      self?.imageView.transform = CGAffineTransform(rotationAngle: CGFloat(rotation))
    }
  }
}

我通过调用 manager.startGyroUpdates() 而不是 manager.startDeviceMotionUpdates()

解决了问题