iOS之加速计、陀螺仪(UIAccelermeter、Core Motion)

本文详细介绍了加速计的基本概念、经典应用场景、工作原理及在iOS平台的开发方法,包括使用UIAccelerometer与CoreMotion框架进行数据采集与处理。重点探讨了如何在不同场景下利用加速计特性实现摇一摇功能、计步器等应用,并对比了两种不同API的使用方法和注意事项。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、加速计的作用
用于检测设备的运动(比如摇晃)

二、加速计的经典应用场景
摇一摇
计步器

三、加速计的原理
检测设备在X、Y、Z轴上的加速度 (哪个方向有力的作用,哪个方向运动了)
根据加速度数值,就可以判断出在各个方向上的作用力度


四、加速计程序的开发
在iOS4以前:使用UIAccelerometer,用法非常简单(到了iOS5就已经过期)
从iOS4开始:CoreMotion.framework
注:必须真机测试,不适用模拟器;
虽然UIAccelerometer已经过期,但由于其用法极其简单,很多程序里面都还有残留

1..UIAccelerometer的
1.1、UIAccelerometer的开发步骤
//获得单例对象
UIAccelerometer *accelerometer = [UIAccelerometer sharedAccelerometer];
 
//设置代理
accelerometer.delegate = self;
 
//设置采样间隔
accelerometer.updateInterval = 1.0/30.0; // 1秒钟采样30次
 
//实现代理方法
- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration
// acceleration中的x、y、z三个属性分别代表每个轴上的加速度
#import "ViewController.h"
#import "UIView+AdjustFrame.h"
 
@interface ViewController () <UIAccelerometerDelegate>
 
@property (weak, nonatomic) IBOutlet UIImageView *ball;
 
// 保留x,y轴上面的速度
@property(nonatomic,assign)CGPoint velocity;
 
@end
 
@implementation ViewController
 
- (void)viewDidLoad {
[super viewDidLoad];
// 1.获取单例对象
UIAccelerometer *acclerometer = [UIAccelerometer sharedAccelerometer];
// 2.设置代理
acclerometer.delegate = self;
// 3.设置采样间隔
acclerometer.updateInterval = 1 / 30.0;
}
 
/**
* 获取到加速计信息的时候会调用该方法
*
* @param acceleration 里面有x,y,z抽上面的加速度
*/
- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration
{
// NSLog(@"x:%f y:%f z:%f", acceleration.x, acceleration.y, acceleration.z);
// 1.计算小球速度(对象的结构内部的属性是不能直接赋值)
_velocity.x += acceleration.x;
_velocity.y += acceleration.y;
// 2.让小球移动
/*
CGRect ballFrame = self.ball.frame;
ballFrame.origin.x += _velocity.x;
self.ball.frame = ballFrame;
*/
self.ball.x += _velocity.x;
self.ball.y -= _velocity.y;
// 3.边界判断
if (self.ball.x <= 0) {
self.ball.x = 0;
_velocity.x *= -0.6;
}
if (self.ball.x >= self.view.width - self.ball.width) {
self.ball.x = self.view.width - self.ball.width;
_velocity.x *= -0.6;
}
if (self.ball.y <= 0) {
self.ball.y = 0;
_velocity.y *= -0.6;
}
if (self.ball.y >= self.view.height - self.ball.height) {
self.ball.y = self.view.height - self.ball.height;
_velocity.y *= -0.6;
}
NSLog(@"x:%f y:%f", _velocity.x, _velocity.y);
}
 
@end

2.Core Motion
随着iPhone4的推出
加速度计全面升级,并引入了陀螺仪
与Motion(运动)相关的编程成为重头戏
苹果特地在iOS4中增加了专门处理Motion的框架-CoreMotion.framework
Core Motion不仅能够提供实时的加速度值和旋转速度值,更重要的是,苹果在其中集成了很多牛逼的算法

2.1、Core Motion获取数据的两种方式
  加速计和陀螺仪的值都是通过Core Motion框架访问的,此框架提供CMMotionManager 类,该类提供的所有的数据都是用来描述用户如何移动设备的。应用程序创建一个CMMotionManager 实例,然后通过以下某种模式使用它:
  • 它可以在动作发生时执行一些代码;
  • 他可以时刻监视一个持续更新的结构,是你随时能够访问到最新的值;
后者是游戏和其他高度交互性应用程序的理性选择;
注:CMMotionManager 类实际上不是一个单例,但应用程序应该把它当做一个单例,我们应该仅为每个应用程序创建一个CMMotionManager 实例,使用普通的alloc和init方法。所以,如果应用中需要多处访问动作管理器时,可能需要在应用程序委托中创建它并提供从这里访问它的权限。
除了CMMotionManager 类,Core Motion还提供了其他的一些类,比如CMAccerometerData和CMCyroData,它们是一些简单容器,用于让应用程序访问动作数据。
      动作管理器需要一个队列,以便在每次发生事件时在其中放入一些要完成的工作,这些工作由你将提供给它的代码块指定。CMMotionManager 的文档明确警告不要将其放入系统的默认队列里,这样可能是默认队列最终被这些事件填满,因而无法处理其他事件。
push   :实时采集所有数据(时刻监视,采集频率高)

pull     :在有需要的时候,再主动去采集数据(基于事件的动作)

2.2、Core Motion的开发步骤
//push
//创建运动管理者对象
CMMotionManager *mgr = [[CMMotionManager alloc] init];
 
//判断加速计是否可用(最好判断)
if (mgr.isAccelerometerAvailable) {
// 加速计可用
}
 
//设置采样间隔
mgr.accelerometerUpdateInterval = 1.0/30.0; // 1秒钟采样30次
 
//开始采样(采样到数据就会调用handlerhandler会在queue中执行)
- (void)startAccelerometerUpdatesToQueue:(NSOperationQueue *)queue withHandler:(CMAccelerometerHandler)handler;
//pull
//创建运动管理者对象
CMMotionManager *mgr = [[CMMotionManager alloc] init];
 
//判断加速计是否可用(最好判断)
if (mgr.isAccelerometerAvailable) { // 加速计可用 }
 
//开始采样
- (void)startAccelerometerUpdates;
 
//在需要的时候采集加速度数据
CMAcceleration acc = mgr.accelerometerData.acceleration;
NSLog(@"%f, %f, %f", acc.x, acc.y, acc.z);
//实例化加速计
#import "ViewController.h"
#import <CoreMotion/CoreMotion.h>
 
@interface ViewController ()
 
@property(nonatomic,strong)CMMotionManager *mgr;
@property (strong, nonatomic) NSOperationQueue *queue;
@end  
 
@implementation ViewController
 
- (void)viewDidLoad {
[super viewDidLoad];
self.queue = [[NSOperationQueue alloc] init];
// 1.陀螺仪是否可用
if (!self.mgr.isGyroAvailable) return;
// 2.开始采样
[self.mgr startGyroUpdates];
}
 
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
// CMAcceleration acceleration = self.mgr.accelerometerData.acceleration;
CMRotationRate rate = self.mgr.gyroData.rotationRate;
NSLog(@"x:%f y:%f z:%f", rate.x, rate.y, rate.z);
}
 
#pragma mark - 获取陀螺仪信息
- (void)pushGyro
{
// 1.陀螺仪是否可用
if (!self.mgr.isGyroAvailable) return;
// 2.设置采样间隔
self.mgr.gyroUpdateInterval = 1.0;
// 3.开始采样
[self.mgr startGyroUpdatesToQueue:self.queue withHandler:^(CMGyroData *gyroData, NSError *error) {
if (error) return;
CMRotationRate rotationRate = gyroData.rotationRate;
NSLog(@"x:%f y:%f z:%f", rotationRate.x, rotationRate.y, rotationRate.z);
}];
}
 
#pragma mark - 获取加速计信息
- (void)pullAccelerometer
{
// 1.判断加速计是否可用
if (!self.mgr.isAccelerometerAvailable) return;
// 2.开始采样
[self.mgr startAccelerometerUpdates];
}
 
- (void)pushAccelerometer
{
/*
// 1.创建运行管理者
CMMotionManager *mgr =
*/
// 2.判断加速计是否可用
if (!self.mgr.isAccelerometerAvailable) return;
// 3.设置采样间隔
self.mgr.accelerometerUpdateInterval = 1/30.0;
// 4.开始采样
#warning
[self.mgr startAccelerometerUpdatesToQueue:self.queue withHandler:^(CMAccelerometerData *accelerometerData, NSError *error) {
if (error) return ;
// 获取到加速计信息
CMAcceleration acceleration = accelerometerData.acceleration;
NSLog(@"x:%f y:%f z:%f", acceleration.x, acceleration.y, acceleration.z);
}];
}
 
#pragma mark - 懒加载
- (CMMotionManager *)mgr
{
if (_mgr == nil) {
_mgr = [[CMMotionManager alloc] init];
}
return _mgr;
}
 
@end
实现摇一摇
#import "ViewController.h"
 
@interface ViewController ()
 
@end
 
@implementation ViewController
 
- (void)viewDidLoad {
[super viewDidLoad];
}
 
- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
NSLog(@"%s", __func__);
}
 
- (void)motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
NSLog(@"%s", __func__);
}
 
- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
NSLog(@"%s", __func__);
}
 
@end
实现计步器
#import "ViewController.h"
#import <CoreMotion/CoreMotion.h>
 
@interface ViewController ()
 
@property (weak, nonatomic) IBOutlet UILabel *stepLabel;
 
@end
 
@implementation ViewController
 
- (void)viewDidLoad {
[super viewDidLoad];
// 1.判断计步器是否可用
if (![CMStepCounter isStepCountingAvailable]) return;
// 2.创建计步器对象
CMStepCounter *stepCounter = [[CMStepCounter alloc] init];
// 3.开始计步(走多少步之后调用一次该方法)
[stepCounter startStepCountingUpdatesToQueue:[NSOperationQueue mainQueue] updateOn:5 withHandler:^(NSInteger numberOfSteps, NSDate *timestamp, NSError *error) {
self.stepLabel.text = [NSString stringWithFormat:@"您已经走了%ld步", numberOfSteps];
}];
}
 
@end
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值