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

简介:

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

加速计

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

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

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

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

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

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

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

motionEnded方法中处理:

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

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

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

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

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

pull处理方式:

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

触摸结束:

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

push处理方式:

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

时间设置频率:

 

陀螺仪

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

 

 

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

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

本文转自Fly_Elephant博客园博客,原文链接:http://www.cnblogs.com/xiaofeixiang/p/4317151.html,如需转载请自行联系原作者

相关文章
|
26天前
|
API 数据安全/隐私保护 iOS开发
利用uni-app 开发的iOS app 发布到App Store全流程
利用uni-app 开发的iOS app 发布到App Store全流程
83 3
|
3月前
|
存储 iOS开发
iOS 开发,如何进行应用的本地化(Localization)?
iOS 开发,如何进行应用的本地化(Localization)?
122 2
|
3月前
|
机器学习/深度学习 PyTorch TensorFlow
是否有其他框架可以在iOS设备上进行机器学习?
是否有其他框架可以在iOS设备上进行机器学习?
21 1
|
3月前
|
存储 数据建模 iOS开发
iOS设备功能和框架: 什么是 Core Data,它在 iOS 中的作用是什么?
iOS设备功能和框架: 什么是 Core Data,它在 iOS 中的作用是什么?
32 1
|
3月前
|
定位技术 iOS开发
iOS设备功能和框架: 如何使用 Core Location 获取设备的位置信息?
iOS设备功能和框架: 如何使用 Core Location 获取设备的位置信息?
19 0
|
3月前
|
存储 数据建模 数据库
IOS开发数据存储:什么是 UserDefaults?有哪些替代方案?
IOS开发数据存储:什么是 UserDefaults?有哪些替代方案?
38 0
|
3月前
|
API 定位技术 iOS开发
IOS开发基础知识:什么是 Cocoa Touch?它在 iOS 开发中的作用是什么?
IOS开发基础知识:什么是 Cocoa Touch?它在 iOS 开发中的作用是什么?
42 2
|
1天前
|
API 定位技术 iOS开发
IOS开发基础知识:什么是 Cocoa Touch?它在 iOS 开发中的作用是什么?
【4月更文挑战第18天】**Cocoa Touch** 是iOS和Mac OS X应用的核心框架,包含面向对象库、运行时系统和触摸优化工具。它提供Mac验证的开发模式,强调触控接口和性能,涵盖3D图形、音频、网络及设备访问API,如相机和GPS。是构建高效iOS应用的基础,对开发者至关重要。
8 0
|
2月前
|
监控 API Swift
用Swift开发iOS平台上的上网行为管理监控软件
在当今数字化时代,随着智能手机的普及,人们对于网络的依赖日益增加。然而,对于一些特定场景,如家庭、学校或者企业,对于iOS设备上的网络行为进行管理和监控显得尤为重要。为了满足这一需求,我们可以利用Swift语言开发一款iOS平台上的上网行为管理监控软件。
181 2
|
3月前
|
数据可视化 iOS开发
iOS 开发,什么是 Interface Builder(IB)?如何使用 IB 构建用户界面?
iOS 开发,什么是 Interface Builder(IB)?如何使用 IB 构建用户界面?
40 4