iOS获取手机倾斜角度
2017-03-21 本文已影响0人
xxxxxffffff
最近一个埋点上的小需求,百度里找到的都不是很好用.
1.引入头文件<CoreMotion/CoreMotion.h> 以及在linked里加入这个包.
- (void)viewDidLoad {
[superviewDidLoad];
CMMotionManager*motionManager = [[CMMotionManageralloc]init];
NSOperationQueue*queue = [[NSOperationQueuealloc]init];
//加速计
if(motionManager.accelerometerAvailable) {
motionManager.accelerometerUpdateInterval=0.5;
[motionManagerstartAccelerometerUpdatesToQueue:queuewithHandler:^(CMAccelerometerData*accelerometerData,NSError*error){
if(error) {
[motionManagerstopAccelerometerUpdates];
NSLog(@"error");
}else{
doublezTheta =atan2(accelerometerData.acceleration.z,sqrtf(accelerometerData.acceleration.x*accelerometerData.acceleration.x+accelerometerData.acceleration.y*accelerometerData.acceleration.y))/M_PI*(-90.0)*2-90;
doublexyTheta =atan2(accelerometerData.acceleration.x,accelerometerData.acceleration.y)/M_PI*180.0;
NSLog(@"手机与水平面的夹角是%.2f,手机绕自身旋转的角度是%.2f",-zTheta,xyTheta);
}
}];
}else{
NSLog(@"This device has no accelerometer");
}
}