使用定时器,以及形成一个简单的动画。

来源:互联网 发布:永恒之塔5.0捏男数据 编辑:程序博客网 时间:2024/04/28 09:49

本文档版权归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

{

    [myIVrelease];

    [startButtonrelease];

    [stopButtonrelease];

    [aniTimerinvalidate];

    [superdealloc];

}


- (void)didReceiveMemoryWarning

{

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

    [superdidReceiveMemoryWarning];

    

   // 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

{

    [superviewDidLoad];

   stopButton.enabled =NO;

   directionDelta = 2;

}



- (void)viewDidUnload

{

    [myIVrelease];

    myIV = nil;

    [startButtonrelease];

   startButton = nil;

    [stopButtonrelease];

   stopButton = nil;

    [superviewDidUnload];

   // 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;

    [aniTimerinvalidate];

    aniTimer = nil;

}


- (IBAction)start:(id)sender {

   startButton.enabled =NO;

   stopButton.enabled =YES;

   aniTimer = [NSTimerscheduledTimerWithTimeInterval:0.01target:selfselector:@selector(timerFunc)userInfo:nilrepeats: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


原创粉丝点击