您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iPhone 中加速器、陀螺儀與磁力計的使用與實作

編輯:iOS 開發綜合

本文示範如何在 iPhone 上運用 Core Motion 框架取得加速計資料,並據此移動畫面中的元件。使用前需在 Frameworks 中匯入 CoreMotion.framework。

#import <CoreMotion/CoreMotion.h>

@interface RootViewController ()
{
    CMMotionManager *motionManager;
    UIImageView* imageView;
}
@end

在 viewDidLoad 中初始化管理器並啟動更新。Core Motion 的使用可歸納為三步:初始化、取得資料、善後處理:

- (void)viewDidLoad {
    [super viewDidLoad];
    imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"33.jpeg"]];
    imageView.frame = CGRectMake(0, 0, 50, 50);
    imageView.center = self.view.center;
    [self.view addSubview:imageView];

    motionManager = [[CMMotionManager alloc] init];
    [motionManager startAccelerometerUpdates];
    if (!motionManager.accelerometerAvailable) {
        NSLog(@"傳感器不可用");
    } else {
        motionManager.accelerometerUpdateInterval = 1/60.0; // 更新頻率
    }

    UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    button.frame = CGRectMake(60, 50, 150, 30);
    [button setTitle:@"停止" forState:UIControlStateNormal];
    [button addTarget:self action:@selector(didstop) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
}

若採用 push 方式,可在設定的佇列中即時取得加速度並移動 imageView:

[motionManager startAccelerometerUpdatesToQueue:[NSOperationQueue currentQueue] withHandler:^(CMAccelerometerData *latestAcc, NSError *error) {
    CMAccelerometerData *data = latestAcc;
    if (data.acceleration.x > 0) {
        imageView.center = CGPointMake(imageView.center.x + 1, imageView.center.y); // 向右
    }
    if (data.acceleration.x < 0) {
        imageView.center = CGPointMake(imageView.center.x - 1, imageView.center.y); // 向左
    }
    if (data.acceleration.y > 0) {
        imageView.center = CGPointMake(imageView.center.x, imageView.center.y - 1); // 向上
    }
    if (data.acceleration.y < 0) {
        imageView.center = CGPointMake(imageView.center.x, imageView.center.y + 1); // 向下
    }
}];

若要主動取值,可讀取 motionManager.accelerometerData 中的 x、y、z 三軸資料:

-(void)didlook {
    CMAccelerometerData *data = motionManager.accelerometerData;
    NSNumber *x = [NSNumber numberWithDouble:data.acceleration.x];
    NSNumber *y = [NSNumber numberWithDouble:data.acceleration.y];
    NSNumber *z = [NSNumber numberWithDouble:data.acceleration.z];
    NSLog(@"x=%@------y=%@--------z=%@", x, y, z);
}

最後是善後處理:在不需要 Core Motion 時釋放資源:

-(void)didstop {
    [motionManager stopAccelerometerUpdates];
}

透過相同架構,也能取得陀螺儀與磁力計資料,差別僅在改用對應的更新方法與資料型別。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved