随机动画效果

ViewController.m

 1 #import "ViewController.h"
 2 #define MAX_SIZE 25//雪花大小
 3 #define MAX_TIME 20//飘落时间
 4 #define MIN_TIME 5
 5 
 6 @implementation ViewController
 7 
 8 - (void)viewDidLoad
 9 {
10     [super viewDidLoad];
11     //背景颜色
12     [self.view setBackgroundColor:[UIColor colorWithRed:0.45 green:0.45 blue:1 alpha:1]];
13     
14     /*每隔0.05秒执行一次onTimer函数*/
15     [NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(onTimer) userInfo:nil repeats:YES];
16 }
17 
18 #pragma mark - viewDidLoad NSTimer onTimer
19 -(void)onTimer
20 {
21     UIImage *snowImage = [UIImage imageNamed:@"3.png"];
22     UIImageView *view = [[UIImageView alloc]initWithImage:snowImage];
23     [snowImage release];
24     
25     /*随机:开始位置、结束位置、大小、速度、透明度*/
26     int startX = random() % 320;
27     int endX = random() % 320;
28     int width = random() % MAX_SIZE;
29     int time = (random() % (MAX_TIME - MIN_TIME)) + MIN_TIME;
30     float alpha = random() % 1000 / (float)1200;
31     
32     //开始位置 从屏幕上沿出现
33     view.frame = CGRectMake(startX, -1*MAX_SIZE, width, width);
34     view.alpha = alpha;//透明度
35     
36     [self.view addSubview:view];
37     
38     [UIView beginAnimations:nil context:view];
39     //速度
40     [UIView setAnimationDuration:time];
41     
42     //结束位置
43     view.frame = CGRectMake(endX, 480, width, width);
44     //解决内存溢出
45     [UIView setAnimationDidStopSelector:@selector(onAnimationComplete:finished:context:)];
46     [UIView setAnimationDelegate:self];
47     
48     [UIView commitAnimations];
49 }
50 
51 #pragma mark - onTimer UIView onAnimationComplete:finished:context:
52 
53 - (void)onAnimationComplete:(NSString*)animationID finished:(NSNumber*)finished context:(void*)context
54 {
55     UIImageView *snowView = context;
56     if (snowView == nil) {
57         return;
58     }
59     [snowView removeFromSuperview];
60 //    [snowView release];//若两个都执行会崩 
61 }
62 
63 @end

 

posted on 2013-01-28 19:29  灰色的人  阅读(208)  评论(0编辑  收藏  举报

导航