使用定時器,以及形成一個簡單的動畫。

本文檔版權歸NickTang所有,沒有本人書面或電子郵件允許,不許轉載,摘錄,發表。多謝!

我們很難想像一個不包含動畫的iOS應用程序,一個iOS遊戲更是不可能沒有動畫,因此我從今天開始一個新的課題---如何寫動畫相關的代碼。

這裏的第一篇文章其實和iOS提供的動畫API沒有關係,只是使用定時器來形成一個動畫,因爲這是動畫的最記本實現方式。所以這個例子也是順便演示一下定時器如何使用。

1.新建一個view-based Application.(在iOS5中是Single View Application)

2.加入一個小的圖片,比如1.png,長和寬都不要大於100.

3.在viewcontroller.xib上面做如下佈局


4.爲它們增加相應的控制指針,並對兩個button的touch up inside事件響應,最後形成的viewcontroller.h文件如下:

@interface tTimerAnimationViewController : UIViewController {

    NSTimer *aniTimer;

    IBOutlet UIImageView *myIV;

    IBOutlet UIButton *startButton;

    IBOutlet UIButton *stopButton;

    int directionDelta;

}

- (IBAction)stop:(id)sender;

- (IBAction)start:(id)sender;

- (void)timerFunc;

@end

5.下面是viewcontroller.m文件,

@implementation tTimerAnimationViewController


- (void)dealloc

{

    [myIV release];

    [startButton release];

    [stopButton release];

    [aniTimer invalidate];

    [super dealloc];

}


- (void)didReceiveMemoryWarning

{

    // Releases the view if it doesn't have a superview.

    [super didReceiveMemoryWarning];

    

    // Release any cached data, images, etc that aren't in use.

}


#pragma mark - View lifecycle



// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.

- (void)viewDidLoad

{

    [super viewDidLoad];

    stopButton.enabled = NO;

    directionDelta = 2;

}



- (void)viewDidUnload

{

    [myIV release];

    myIV = nil;

    [startButton release];

    startButton = nil;

    [stopButton release];

    stopButton = nil;

    [super viewDidUnload];

    // Release any retained subviews of the main view.

    // e.g. self.myOutlet = nil;

}


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation

{

    // Return YES for supported orientations

    return (interfaceOrientation == UIInterfaceOrientationPortrait);

}


- (IBAction)stop:(id)sender {

    startButton.enabled = YES;

    stopButton.enabled = NO;

    [aniTimer invalidate];

    aniTimer = nil;

}


- (IBAction)start:(id)sender {

    startButton.enabled = NO;

    stopButton.enabled = YES;

    aniTimer = [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(timerFunc) userInfo:nil repeats:YES];

}

- (void)timerFunc

{

    CGPoint center = myIV.center;

    if(center.y >450)

        directionDelta = -2;

    if(center.y < 30)

        directionDelta = 2;

    center.y += directionDelta;

    

    myIV.center = center;

    

}

@end


6.解釋如下:

aniTimer = [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(timerFunc) userInfo:nil repeats:YES];

上面的這句話啓動一個定時器,每0.01秒調用一次,定時器觸發的函數是self的timerFunc。userInfo是傳入到timerFunc的參數,repeats是標識是否重複調用這個定時器。

相關代碼在這裏:

http://download.csdn.net/download/NickTang/3690782


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章