ios加速计和陀螺仪

21 篇文章 0 订阅
ios设备中有的加速计可以测量出加速度和重力。陀螺仪可用于确定设备的方向与每条坐标轴之间的夹角,可用于读取描述设备围绕其轴的旋转的值。
添加CoreMotion.framework.
以下为例子代码:

#import <UIKit/UIKit.h>
#import <CoreMotion/CoreMotion.h>

@interface ViewController : UIViewController

@property (strong, nonatomic) CMMotionManager *motionManager;
@property (weak, nonatomic) IBOutlet UILabel *accelerometerLabel;
@property (weak, nonatomic) IBOutlet UILabel *gyroscopeLabel;

@end




#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController
@synthesize motionManager;
@synthesize accelerometerLabel;
@synthesize gyroscopeLabel;

- (void)viewDidLoad
{
[super viewDidLoad];
self.motionManager = [[CMMotionManager alloc] init];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
//加速计
if (motionManager.accelerometerAvailable) {
motionManager.accelerometerUpdateInterval = 1.0/10.0;
[motionManager startAccelerometerUpdatesToQueue:queue withHandler:^(CMAccelerometerData *accelerometerData,NSError *error){
NSString *labelText;
if (error) {
[motionManager stopAccelerometerUpdates];
labelText = [NSString stringWithFormat:@"Accelerometer encountered error: %@",error];
}else{
labelText = [NSString stringWithFormat:@"加速计\nx: %+.2f\ny: %+.2f\nz: %+.2f",accelerometerData.acceleration.x,accelerometerData.acceleration.y,accelerometerData.acceleration.z];
}
[accelerometerLabel performSelectorOnMainThread:@selector(setText:) withObject:labelText waitUntilDone:NO];
}];
}else{
accelerometerLabel.text = @"This device has no accelerometer.";
}
//陀螺仪
if (motionManager.gyroAvailable) {
motionManager.gyroUpdateInterval = 1.0/10.0;
[motionManager startGyroUpdatesToQueue:queue withHandler:^(CMGyroData *gyroData,NSError *error){
NSString *labelText;
if (error) {
[motionManager stopGyroUpdates];
labelText = [NSString stringWithFormat:@"Gyroscope encountered error: %@",error];
}else{
labelText = [NSString stringWithFormat:@"陀螺仪\nx: %+.2f\ny: %+.2f\nz: %+.2f",gyroData.rotationRate.x,gyroData.rotationRate.y,gyroData.rotationRate.z];
}
[gyroscopeLabel performSelectorOnMainThread:@selector(setText:) withObject:labelText waitUntilDone:NO];
}];
}else{
gyroscopeLabel.text = @"This device has no gyroscope";
}
}

- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}

@end
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值