iOS开发-CoreMotion框架(加速计和陀螺仪)

十度 IOS 2015年12月01日 收藏

CoreMotion是一个专门处理Motion的框架,其中包含了两个部分加速度计和陀螺仪,在iOS4之前加速度计是由UIAccelerometer类来负责采集数据,现在一般都是用CoreMotion来处理加速度过程,不过由于UIAccelerometer比较简单,同样有人在使用。加速计由三个坐标轴决定,用户最常见的操作设备的动作移动,晃动手机(摇一摇),倾斜手机都可以被设备检测到,加速计可以检测到线性的变化,陀螺仪可以更好的检测到偏转的动作,可以根据用户的动作做出相应的动作,iOS模拟器无法模拟以上动作,真机调试需要开发者账号。

加速计

加速计的x,y,z三个方向,参考下图:

如果只需要知道设备的方向,不需要知道具体方向矢量角度,那么可以使用UIDevice进行操作,还可以根据方向就行判断,具体可以参考一下苹果官网代码:

  1. -(void) viewDidLoad {
  2. // Request to turn on accelerometer and begin receiving accelerometer events
  3. [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
  4. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(orientationChanged:) name:UIDeviceOrientationDidChangeNotification object:nil];
  5. }
  6. - (void)orientationChanged:(NSNotification *)notification {
  7. // Respond to changes in device orientation
  8. }
  9. -(void) viewDidDisappear {
  10. // Request to stop receiving accelerometer events and turn off accelerometer
  11. [[NSNotificationCenter defaultCenter] removeObserver:self];
  12. [[UIDevice currentDevice] endGeneratingDeviceOrientationNotifications];
  13. }

 当用户晃动设备的时候,系统会通知每一个在用的设备,可以使本身成为第一响应者:

  1. - (BOOL)canBecomeFirstResponder {
  2. return YES;
  3. }
  4. - (void)viewDidAppear:(BOOL)animated {
  5. [self becomeFirstResponder];
  6. }

处理Motion事件有三种方式,开始(motionBegan),结束(motionEnded),取消(motionCancelled):

  1. - (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event NS_AVAILABLE_IOS(3_0);
  2. - (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event NS_AVAILABLE_IOS(3_0);
  3. - (void)motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event NS_AVAILABLE_IOS(3_0);

motionEnded方法中处理:

  1. - (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event {
  2. if (motion == UIEventSubtypeMotionShake)
  3. {
  4. // FlyElephant http://www.cnblogs.com/xiaofeixiang
  5. [[NSNotificationCenter defaultCenter] postNotificationName:@"FlyElephant" object:self];
  6. }
  7. }

CoreMotion在处理加速计数据和陀螺仪数据的时是一个非常重要的框架,框架本身集成了很多算法获取原生的数据,而且能很好的展现出来,CoreMotion与UIKit不同,连接的是UIEvent而不是事件响应链。CoreMotion相对于接收数据只是更简单的分发motion事件。

CMMotionManager类能够使用到设备的所有移动数据(motion data),Core Motion框架提供了两种对motion数据的操作方式:

pull方式:能够以CoreMotionManager的只读方式获取当前任何传感器状态或是组合数据;

push方式:是以块或者闭包的形式收集到想要得到的数据并且在特定周期内得到实时的更新;

pull处理方式:

  1. //判断加速计是否可用
  2. if ([_motionManager isAccelerometerAvailable]) {
  3. // 设置加速计采样频率
  4. [_motionManager setAccelerometerUpdateInterval:1 / 40.0];
  5. [_motionManager startAccelerometerUpdates];
  6. } else {
  7. NSLog(@"博客园-FlyElephant");
  8. }

触摸结束:

  1. -(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
  2. CMAcceleration acceleration=_motionManager.accelerometerData.acceleration;
  3. NSLog(@"%f---%f---%f",acceleration.x,acceleration.y,acceleration.z);
  4. }

push处理方式:

  1. @property (strong,nonatomic) CMMotionManager *motionManager;
  2.  
  3. @property (strong,nonatomic) NSOperationQueue *quene;
  1. _motionManager=[[CMMotionManager alloc]init];
  2. //判断加速计是否可用
  3. if ([_motionManager isAccelerometerAvailable]) {
  4. // 设置加速计频率
  5. [_motionManager setAccelerometerUpdateInterval:1 / 40.0];
  6. //开始采样数据
  7. [_motionManager startAccelerometerUpdatesToQueue:_quene withHandler:^(CMAccelerometerData *accelerometerData, NSError *error) {
  8. NSLog(@"%f---%f",accelerometerData.acceleration.x,accelerometerData.acceleration.y);
  9. }];
  10. } else {
  11. NSLog(@"博客园-FlyElephant");
  12. }

时间设置频率:

 

陀螺仪

陀螺仪其实主要方法和方式和加速计没有区别,先看张陀螺仪旋转的角度图片:

 

 

陀螺仪更新数据也有两种方式,pull方式(startGyroUpdates),push方式(startGyroUpdatesToQueue):

  1. static const NSTimeInterval gyroMin = 0.01;
  2. - (void)startUpdatesWithSliderValue:(int)sliderValue {
  3. // Determine the update interval
  4. NSTimeInterval delta = 0.005;
  5. NSTimeInterval updateInterval = gyroMin + delta * sliderValue;
  6. // Create a CMMotionManager
  7. CMMotionManager *mManager = [(APLAppDelegate *)[[UIApplication sharedApplication] delegate] sharedManager];
  8. APLGyroGraphViewController * __weak weakSelf = self;
  9. // Check whether the gyroscope is available
  10. if ([mManager isGyroAvailable] == YES) {
  11. // Assign the update interval to the motion manager
  12. [mManager setGyroUpdateInterval:updateInterval];
  13. [mManager startGyroUpdatesToQueue:[NSOperationQueue mainQueue] withHandler:^(CMGyroData *gyroData, NSError *error) {
  14. [weakSelf.graphView addX:gyroData.rotationRate.x y:gyroData.rotationRate.y z:gyroData.rotationRate.z];
  15. [weakSelf setLabelValueX:gyroData.rotationRate.x y:gyroData.rotationRate.y z:gyroData.rotationRate.z];
  16. }];
  17. }
  18. self.updateIntervalLabel.text = [NSString stringWithFormat:@"%f", updateInterval];
  19. }
  20. - (void)stopUpdates{
  21. CMMotionManager *mManager = [(APLAppDelegate *)[[UIApplication sharedApplication] delegate] sharedManager];
  22. if ([mManager isGyroActive] == YES) {
  23. [mManager stopGyroUpdates];
  24. }
  25. }

  很晚了,先睡觉了~有空补充一下~