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

本文档版权归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= [NSTimerscheduledTimerWithTimeInterval:0.01target:selfselector:@selector(timerFunc)userInfo:nilrepeats:YES];

上面的这句话启动一个定时器,每0.01秒调用一次,定时器触发的函数是self的timerFunc。userInfo是传入到timerFunc的参数,repeats是标识是否重复调用这个定时器。

相关代码在这里:

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


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值