ios加速计和陀螺仪
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