效果如下:
ViewController.h
1 #import <UIKit/UIKit.h> 2 3 @interface ViewController : UIViewController 4 @property (strong, nonatomic) UIImage *imgSnowflake; 5 6 @end
ViewController.m
1 #import "ViewController.h" 2 3 @interface ViewController () 4 - (void)layoutUI; 5 - (void)snow; 6 @end 7 8 @implementation ViewController 9 #define kApplicationFrame [[UIScreen mainScreen] applicationFrame] 10 #define kWidthOfSnowflake 30.0 11 12 - (void)viewDidLoad { 13 [super viewDidLoad]; 14 15 [self layoutUI]; 16 } 17 18 - (void)didReceiveMemoryWarning { 19 [super didReceiveMemoryWarning]; 20 // Dispose of any resources that can be recreated. 21 } 22 23 - (void)layoutUI { 24 self.view.backgroundColor = [UIColor colorWithRed:0.218 green:0.219 blue:0.196 alpha:1.000]; 25 _imgSnowflake = [UIImage imageNamed:@"Snowflake"]; 26 27 //定时器;每隔0.5秒执行一次 28 [NSTimer scheduledTimerWithTimeInterval:0.5 29 target:self 30 selector:@selector(snow) 31 userInfo:nil 32 repeats:YES]; 33 } 34 35 - (void)snow { 36 NSString *strWidthOfScene = [NSString stringWithFormat:@"%f", kApplicationFrame.size.width-kWidthOfSnowflake]; 37 CGFloat startX = arc4random()%[strWidthOfScene integerValue]; //产生随机数0到strWidthOfScene-1 38 CGFloat endX = arc4random()%([strWidthOfScene integerValue]+1); //产生随机数1到strWidthOfScene 39 40 UIImageView *imgV = [[UIImageView alloc] initWithImage:_imgSnowflake]; 41 imgV.frame = CGRectMake(startX, -20.0, kWidthOfSnowflake, kWidthOfSnowflake); 42 imgV.alpha = 0.8; 43 [self.view addSubview:imgV]; 44 45 [UIView beginAnimations:nil context:NULL]; 46 [UIView setAnimationDuration:5]; 47 imgV.frame = CGRectMake(endX, 48 kApplicationFrame.size.height+20.0-kWidthOfSnowflake, 49 kWidthOfSnowflake, 50 kWidthOfSnowflake); 51 [UIView commitAnimations]; 52 } 53 54 @end
时间: 2024-11-06 09:32:56