iphonedevelopment专题小站

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

本文转载子iPhone手机开发者论坛www.madhome.org

 

说明:示范抓取加速计的资料来判断iPhoneShake摇动动作

示范


摇晃前的预设文字:没事


用力摇晃后画面将显示为:摇动

程式码:

#import "AccelerometerDemoViewController.h"

@implementation AccelerometerDemoViewController

@synthesize mylabel;

- (void)viewDidLoad {
        UIAccelerometer *accelerometer = [UIAccelerometer sharedAccelerometer];
        accelerometer.delegate = self;
        accelerometer.updateInterval =  1.0f/60.0f;
    [super viewDidLoad];        
}

- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration{
        
        static NSInteger shakeCount=0;
        static NSDate *shakeStart;
        
        NSDate *now=[[NSDate alloc] init];
        //
搖晃時間在2秒內
        NSDate *checkDate=[[NSDate alloc] initWithTimeInterval:2.0f sinceDate:shakeStart];
        
        //
超過2秒則重新計算搖晃次數
        if ([now compare:checkDate]==NSOrderedDescending||shakeStart==nil){
                shakeCount=0;
                [shakeStart release];
                shakeStart=[[NSDate alloc] init];                                
        }
        
        [now release];
        [checkDate release];
        
        //
三軸搖晃的G力超過2則列入計次
        if (fabsf(acceleration.x)>2.0 || fabsf(acceleration.y)>2.0|| fabsf(acceleration.z)>2.0){
                shakeCount++;
                
                //
2秒內偵測到4次則判定為Shake搖晃手機
                if (shakeCount>4){
                        shakeCount=0;
                        [shakeStart release];
                        shakeStart=[[NSDate alloc] init];
                        
                        //
畫面顯示搖動文字
                        mylabel.text=@"
搖動";
                        
        //
設定2秒後自動還原                
        [NSTimer scheduledTimerWithTimeInterval:2.0f target:self selector:@selector(cleartext) userInfo:nil repeats:NO];
                }
        }
}                
                        
-(void)cleartext{
        //
預設文字
        mylabel.text=@"
沒事";
}


此范例的应用相当的广泛而有趣,早期App Store上的创意软体如花女棒、打火机及蜡烛等软体都是利用相同的原理实作的喔,看看您是否也能想出更好的创意。

附件下载地址:iPhone手机开发者论坛http://www.madhome.org/

 

posted on 2010-03-23 13:16  rek  阅读(358)  评论(1编辑  收藏  举报