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

如何实现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框架

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值