使用定时器制作雪花动画

 1 #import "HUAppDelegate.h"
 2 
 3 @implementation HUAppDelegate
 4 
 5 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
 6 {
 7     self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
 8     // Override point for customization after application launch.
 9     self.window.backgroundColor = [UIColor colorWithRed:0 green:0.7 blue:1 alpha:0.7];
10     [self.window makeKeyAndVisible];
11     
12     
13     //创建数组,盛放雪花
14     _snowArray = [[NSMutableArray alloc] init];
15     for (int i=0; i < 30; i++)
16     {
17         UIImageView *snow = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"flake.png"]];
18         snow.frame = CGRectMake(arc4random() % 320, -20, 20, 20);
19         [_snowArray addObject:snow];
20         [self.window addSubview:snow];
21         
22     }
23     //这个定时器使用来寻找可以进行下落的雪花
24     [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(findSnow) userInfo:nil repeats:YES];
25 
26     //这个定时器是将找到的雪花下落
27     [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(snowDown) userInfo:nil repeats:YES];
28     
29     return YES;
30 }
31 
32 - (void)findSnow
33 {
34     for (int i = 0; i < _snowArray.count; i++)
35     {
36         UIImageView *imageView = [_snowArray objectAtIndex:i];
37         if (imageView.tag == 0)  //使用 tag 值来标识雪花是否可以进行下落,0 表示可以,1表示不可以
38         {
39             imageView.tag = 1;  //tag 为 1 表示希望雪花进行下落
40             break;
41         }
42     }
43 }
44 - (void)snowDown
45 {
46     for (int i = 0; i < _snowArray.count; i ++)
47     {
48         UIImageView *imageView = [_snowArray objectAtIndex:i];
49         if (imageView.tag == 1)   //tag 为1表示这多雪花需要进行下落的动作
50         {
51             CGRect rect = imageView.frame;
52             rect.origin.y += 1;  //通过改变纵坐标的值模拟动画,注意 OC 不允许深度赋值
53             imageView.frame = rect;
54             if (rect.origin.y > 480)
55             {
56                 rect.origin.x = arc4random() % 320;
57                 rect.origin.y = -20;  //让已经下落到底部的雪花回到顶部,重新下落
58                 imageView.frame = rect;
59                 [_snowArray replaceObjectAtIndex:i withObject:imageView]; //这里是让已经下落到底部的雪花在重新利用,即循环下落,造成雪花无穷无尽的效果,尽管数组里只存储了 30 多雪花.观察这里发现,寻找雪花的定时器在进行了 30 次查找后发现,已经在也找不到一朵 tag 值为 0 的雪花了,此时最好是将这个定时器给销毁,否则它会一直重复寻找下去,消耗内存资源。另外一种方法是将已经下落到底部的雪花的 tag 值在重置为 0,但这种解法显然是没有前一种好的。
60             }
61         }
62     }
63 }
64 
65 @end

这种方法的好处是雪花的个数是可以控制的,并且通过方法达到无穷无尽(即重用)的效果,不需要像 UIView 动画那样没次都需要创建一个雪花的 UIImageView 对象, 这样可以节省内存,缺点是这样实现的动画效果比较僵硬,在这里值实现了雪花的纵向移动,并没有横向的效果。

可以对比前一篇雪花的动画效果,查看请戳这里

posted @ 2014-12-17 21:09  红红de  阅读(155)  评论(0编辑  收藏  举报