加速度计只能测量设备上的线性加速度,设备的倾斜,偏转,旋转加速度计无法测量到,这需要使用陀螺仪,陀螺仪又叫角加速度传感器.
陀螺仪在代码上和加速度计差不多,直接贴代码
- (void)viewDidLoad
{
[super viewDidLoad];
self.motionManager = [[CMMotionManager alloc] init];
self.motionManager.gyroUpdateInterval = 0.1;//设置读取时间
if ([self.motionManager isGyroAvailable]){//判断是否可用
[self.motionManager startGyroUpdatesToQueue:[NSOperationQueue mainQueue]
withHandler:^(CMGyroData *gyroData, NSError *error) {
if (error) {
[self.motionManager stopGyroUpdates];//关闭读取
} else {
CMRotationRate rotate = gyroData.rotationRate;
NSLog(@"x=%f", rotate.x);
self.xLabel.text = [NSString stringWithFormat:@"%f", rotate.x];
self.xBar.progress = ABS(rotate.x);
NSLog(@"y=%f", rotate.y);
self.yLabel.text = [NSString stringWithFormat:@"%f", rotate.y];
self.yBar.progress = ABS(rotate.y);
NSLog(@"z=%f", rotate.z);
self.zLabel.text = [NSString stringWithFormat:@"%f", rotate.z];
self.zBar.progress = ABS(rotate.z);
}
}];
} else {
NSLog(@"Gyroscope is not available.");
}
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
[self.motionManager stopGyroUpdates];
}
检测晃动设备
运动事件的检测方法和触摸事件类似,都是继承了UIResponder
-(void)motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event
-(void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event
-(void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event
- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event{
if (motion == UIEventSubtypeMotionShake) {
self.label.text = @"晃动开始";
}
}
- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event{
if (motion == UIEventSubtypeMotionShake) {
self.label.text = @"晃动结束";
}
}
- (void)motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event{
if (motion == UIEventSubtypeMotionShake) {
self.label.text = @"晃动取消";
}
}
typedef NS_ENUM(NSInteger, UIEventSubtype) {
// available in iPhone OS 3.0
UIEventSubtypeNone = 0,
// for UIEventTypeMotion, available in iPhone OS 3.0
UIEventSubtypeMotionShake = 1,
// for UIEventTypeRemoteControl, available in iOS 4.0
UIEventSubtypeRemoteControlPlay = 100,
UIEventSubtypeRemoteControlPause = 101,
UIEventSubtypeRemoteControlStop = 102,
UIEventSubtypeRemoteControlTogglePlayPause = 103,
UIEventSubtypeRemoteControlNextTrack = 104,
UIEventSubtypeRemoteControlPreviousTrack = 105,
UIEventSubtypeRemoteControlBeginSeekingBackward = 106,
UIEventSubtypeRemoteControlEndSeekingBackward = 107,
UIEventSubtypeRemoteControlBeginSeekingForward = 108,
UIEventSubtypeRemoteControlEndSeekingForward = 109,
};
其中
UIEventSubtypeNone代表触摸事件,UIEventSubtypeMotionShake代表晃动事件,UIEventSubtypeRemoteControlPlay与UIEventSubtypeRemoteControlEndSeekingForward代表多媒体远程控制事件
简单来说,这章只是很浅的告诉了我们什么是加速度计与陀螺仪,但商用的话我想还需要更多的探索,大家可以自行去网上google
更多干货,请支持原作:http://item.jd.com/11436547.html