您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 訊息 >> iOS 相關資訊

iOS CoreMotion:讀取陀螺儀與裝置運動資料

編輯:iOS 相關資訊

CoreMotion 是 iOS 提供運動感測資料的框架,加速度計、陀螺儀、磁力計的融合結果都可以從這裡取得。

引入框架

#import <CoreMotion/CoreMotion.h>

宣告屬性

@property (nonatomic, strong) CMMotionManager *mMotionManager;

這裡有個容易踩到的細節:一定要用 property 持有 CMMotionManager,不要用區域變數。CMMotionManager 一旦沒有人強引用而被回收,更新 callback 就會立即停止,資料再也拿不到,而且不會有任何錯誤訊息。

取得裝置運動資料並計算旋轉角度

// Load Motion
_mMotionManager = [[CMMotionManager alloc] init];

if (_mMotionManager.deviceMotionAvailable) {
    _mMotionManager.deviceMotionUpdateInterval = 0.01f;

    [_mMotionManager startDeviceMotionUpdatesToQueue:[NSOperationQueue mainQueue]
        withHandler:^(CMDeviceMotion *data, NSError *error) {
            double rotation = atan2(data.gravity.x, data.gravity.y) - M_PI;
            _rotation = rotation;
        }];
}

這裡用重力向量的 x 與 y 分量做 atan2,得到裝置在螢幕平面上的傾斜角,再扣掉 π 讓零點對齊。用重力而不是 attitude 的好處是數值單純、不會受陀螺儀漂移影響。

停止更新

[_mMotionManager stopDeviceMotionUpdates];

停止更新的時機很重要。運動感測是相當耗電的來源,通常在 viewDidDisappear 或 App 進入背景時就該停掉,回到前台再重啟。

幾個實務提醒

deviceMotionUpdateInterval 設為 0.01 代表每秒取樣 100 次。這個值越低負擔越重,多數介面互動場景其實 1/30 到 1/60 秒就綽綽有餘。另外要區分幾組 API:deviceMotion 是裝置相對於地面的姿態,CMAttitude 用四元數表示;accelerometer 則是包含重力的原始加速度。若要做手勢辨識或水平儀,通常 deviceMotion 就夠了。

最後補充一點:Apple 會檢視 App 對 CoreMotion 的使用方式,若只是為了裝飾性效果而持續高頻取樣,審核與電量表現上都可能成為問題。

參考文章:https://nshipster.com/cmdevicemotion/

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved