雪花飘落-动画制作(UIImage+NSTimer定时器)

时间:2022-11-01 00:06:29

本文主要使用UIImage和定时器制作一个简单的雪花飘落Demo.


效果:
雪花飘落-动画制作(UIImage+NSTimer定时器)


雪花飘落-动画制作(UIImage+NSTimer定时器)


雪花飘落-动画制作(UIImage+NSTimer定时器)
效果解释:随机生成雪花数目,飘到屏幕底部指定位置,设置时间,底部的雪花“消融”。


源代码:

#define FPS 30.0
#define MAX_SIZE 10
#define MAX_DURATION 10


- (void)viewDidLoad
{
[super viewDidLoad];
//启动定时器,创建雪花
[NSTimer scheduledTimerWithTimeInterval:1/FPS target:self selector:@selector(animate:) userInfo:nil repeats:YES];
}

-(void)animate:(NSTimer *)timer{
//1.创建一个雪花
UIImageView *snow = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"snow.png"]];
int viewWidth = self.view.bounds.size.width;
int viewHeight = self.view.bounds.size.height;
CGFloat size = MAX_SIZE+arc4random()%MAX_SIZE;
snow.frame = CGRectMake(arc4random()%viewWidth, -20, size, size);
[self.view addSubview:snow];
//2.创建动画
[UIView animateWithDuration:arc4random()%MAX_DURATION+2 delay:0 options:UIViewAnimationOptionCurveEaseIn animations:^{
//3. 设置动画结束时雪花的位置信息
int offset = arc4random()%100 - 50;
snow.center = CGPointMake(snow.center.x+offset, viewHeight-30);
}completion:^(BOOL finished) {
//4.落地动画结束时,开始融雪
[UIView animateWithDuration:arc4random()%MAX_DURATION delay:0 options:UIViewAnimationOptionCurveEaseIn animations:^{
snow.alpha = 0;
} completion:^(BOOL finished) {
//5.融雪动画结束时,将图片移出父视图
[snow removeFromSuperview];
}];
}];
}

谢谢大家!