2012年2月8日 星期三

Filter4Cam 學習之 Animating a Compass to Point North in iOS 5

since: 2012/02/08
update: 2012/02/08

reference: Animating a Compass to Point North in iOS 5 « Safari Books Online's Official Blog

A. 前言
     大部份的擴增實境(AR) app 會顯示一個羅盤用來指出你目前的方位. 要做到這樣,
     似乎是一件複雜的事情, 不過實際上是相當簡單的. 之前的文章
     Augmented Reality in iOS 5 展示了如何在 iOS 5 中, 使用 CoreLocation 框架來從
     iPhone 的羅盤取得地磁的方向. 藉由使用這個航向的資訊, 我們可以旋轉任何種類
     的 view 並將它指向地磁北極.
  
-----------------------------------------------------------------------------------------------

B. 加入磁針
   1. 開啓之前的 MyAR 專案, 並將磁針(needle)圖片加入專案中.

   2. 開啓 ViewController.h 檔案, 修改如下:
....
@interface ViewController : UIViewController <CLLocationManagerDelegate>
{
    //@add
    // We need to specify this class as the delegate for the CLLocationManager
    CLLocationManager *locationManager;
    UILabel *label;
    UIImageView *needle;
}

//@add
@property (nonatomic, strong) CLLocationManager *locationManager;
@property (nonatomic, strong) UILabel *label;
@property (nonatomic, strong) UIImageView *needle;
....

   3. 開啓 ViewController.m 檔案, 修改如下:
....
@synthesize locationManager = _locationManager;
@synthesize label = _label;
@synthesize needle = _needle;
....
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    //@add
....
    //@add
    UIImageView *needle = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"needle.png"]];

    needle.frame = CGRectMake(10, 10, 70, 70);
    needle.backgroundColor = [UIColor clearColor];
    needle.opaque = NO;
   
    [self setNeedle:needle];
}
....

-----------------------------------------------------------------------------------------------

C. 將磁針指向磁北極
   1. 開啓 ViewController.m 檔案, 修改如下:
- (void) locationManager:(CLLocationManager *)manager didUpdateHeading:(CLHeading *)newHeading
{
    //NSLog(@"Magnetic Heading: %f", newHeading.magneticHeading);
    //@update
    self.label.text = [NSString stringWithFormat:@"%f°", newHeading.magneticHeading];
   
    //@add
    // taking the magnetic heading of the compass
    double degrees = newHeading.magneticHeading;

    // converting it to radians
    double radians = degrees * M_PI / 180;

    // setting the transform using the CGAffineTransformMakeRotation function
    self.needle.transform = CGAffineTransformMakeRotation(-radians);
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
....
    //The overlay view for the UIImagePickerController accepts any UIView
    //[picker setCameraOverlayView:self.label];
    [picker setCameraOverlayView:self.needle];
   
    [self presentModalViewController:picker animated:YES];
}

-----------------------------------------------------------------------------------------------

D. 編譯並執行


沒有留言:

張貼留言

注意:只有此網誌的成員可以留言。