IOS 特定於裝置的開發:獲取和使用裝置姿勢(通過手機方向控制3d物體顯示)

haibo wang發表於2014-12-23

利用裝置的機載陀螺儀可以實現,當你旋轉手機螢幕時,裡面的畫面不會隨著檢視更新而移動,以平衡物理運動。

下面例子利用少量簡單的幾何變換執行該操作。他建立一個運動管理器,訂閱裝置運動更新,然後基於運動管理器返回的搖晃,前傾和左右搖擺的角度應用影象變換。

@implementation TestBedViewController
{
    CMMotionManager *motionManager;
    UIImageView *imageView;
}

- (void) shutDownMotionManager
{
    NSLog(@"Shutting down motion manager");
    [motionManager stopDeviceMotionUpdates];
    motionManager = nil;
}

- (void) establishMotionManager
{
    if (motionManager)
        [self shutDownMotionManager];
    
    NSLog(@"Establishing motion manager");
    
    // Establish the motion manager
    motionManager = [[CMMotionManager alloc] init];
    if (motionManager.deviceMotionAvailable)
        [motionManager
         startDeviceMotionUpdatesToQueue:[NSOperationQueue currentQueue]
         withHandler: ^(CMDeviceMotion *motion, NSError *error) {
             CATransform3D transform;
             transform = CATransform3DMakeRotation(motion.attitude.pitch, 1, 0, 0);
             transform = CATransform3DRotate(transform, motion.attitude.roll, 0, 1, 0);
             transform = CATransform3DRotate(transform, motion.attitude.yaw, 0, 0, 1);
             imageView.layer.transform = transform;
         }];
}

- (void) viewDidAppear: (BOOL) animated
{
    NSString *imageName = IS_IPAD ? @"iPadArt.png" : @"iPhoneArt.png";
    UIImage *image = [UIImage imageNamed:imageName];
    imageView = [[UIImageView alloc] initWithImage:image];
    imageView.center = RECTCENTER(self.view.bounds);
    [self.view addSubview:imageView];
}

- (void) loadView
{
    [super loadView];
    self.view.backgroundColor = [UIColor whiteColor];
}

 

相關文章