[IOS]陀螺仪和加速仪编程

发布时间:2020-10-14 07:01:14 作者:蓬莱仙羽
来源:网络 阅读:466

如何实现iPhone的重力感应还有旋转感应,也就是术语上的陀螺仪和加速器?下面我们来用一个简单的Demo入门一下吧!

由于模拟器上不能运行这个,所以只能贴出代码,没有截图。

ViewController.h:

#import <UIKit/UIKit.h> @interface BIDViewController : UIViewController<UIAccelerometerDelegate> @property (weak, nonatomic) IBOutlet UILabel *accelerometerLabel; @property (weak, nonatomic) IBOutlet UILabel *gyroscopeLabel; @end

ViewController.m:

#import "BIDViewController.h" #import <CoreMotion/CoreMotion.h>  @interface BIDViewController () @property (strong, nonatomic) CMMotionManager *motionManager; @property (strong, nonatomic) NSOperationQueue *queue; @end  @implementation BIDViewController  - (NSUInteger)supportedInterfaceOrientations {     return UIInterfaceOrientationMaskPortrait; }  - (void)viewDidLoad {     [super viewDidLoad]; 	// Do any additional setup after loading the view, typically from a nib.          self.motionManager = [[CMMotionManager alloc] init];     self.queue = [[NSOperationQueue alloc] init];          if (self.motionManager.accelerometerAvailable) {                  self.motionManager.accelerometerUpdateInterval = 1.0 / 10.0;                  [self.motionManager startAccelerometerUpdatesToQueue:self.queue                                                  withHandler:          ^(CMAccelerometerData *accelerometerData, NSError *error) {                           NSString *labelText;             labelText = [NSString stringWithFormat:                         @"Accelerometer\n-----------\nx: %+.2f\ny: %+.2f\nz: %+.2f",                         accelerometerData.acceleration.x,                         accelerometerData.acceleration.y,                         accelerometerData.acceleration.z];              NSLog(@"%@",labelText);           }];     } else {         self.accelerometerLabel.text = @"This device has no accelerometer.";     }     if (self.motionManager.gyroAvailable) {         self.motionManager.gyroUpdateInterval = 1.0 / 10.0;         [self.motionManager startGyroUpdatesToQueue:self.queue withHandler:          ^(CMGyroData *gyroData, NSError *error) {                            NSString *labelText;             labelText = [NSString stringWithFormat:                         @"Gyroscope\n--------\nx: %+.2f\ny: %+.2f\nz: %+.2f",                         gyroData.rotationRate.x,                         gyroData.rotationRate.y,                         gyroData.rotationRate.z];              NSLog(@"%@",labelText);           }];     } else {         self.gyroscopeLabel.text = @"This device has no gyroscope";     } }   @end

切记要导入CoreMotion.framework框架

推荐阅读:
  1. 如何实现nginx与tomcat云服务器集群做负载均衡的方法详细解答。
  2. Unity3D使用陀螺仪控制节点旋转

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

陀螺仪

上一篇:Flask模板引擎之Jinja2语法介绍

下一篇:Django无法处理HTTP PUT/DELETE请求

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》