该app为应用的功能为制作一场雪景
现版本 SDK 8.4 Xcode
纲要:
- UIImageView 的运用- onTimer 代码运用- onAnimation 代码运用运行Xcode 选择 Create a new Xcode project ->Single View Application 命名 SnowFall
(1) 在xCode打开 ViewController.h 文件
(红色为所添加的代码)
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController{
UIImage *flakeImage;
}
@property(nonatomic,retain)UIImage *flakeImage;
-(void)onTimer;
-(void)onAnimationComplete:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context;
@end
(2) 在xCode打开 ViewController.m 文件
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
@synthesize flakeImage;
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
// RGB和alpha值的范围是0~1 Alpha透明度
// 把背景颜色设置为冷色
self.view.backgroundColor = [UIColor colorWithRed:0.5 green:0.5 blue:1.0 alpha:1.0];
// 导出雪花图片
flakeImage = [UIImage imageNamed:@"flake.png"];
// 每秒二十次的调用onTimer事件
[NSTimer scheduledTimerWithTimeInterval:(0.05) target:self selector:@selector(onTimer) userInfo:nil repeats:YES];
}
-(void)onTimer
{
//建立一个ImageView 放置雪花图片 flake image
UIImageView *flakeView = [[UIImageView alloc]initWithImage:flakeImage];
//随即生成参数坐标
int startX = round(random()%320);
int endX = round(random()%320);
double scale = 1/round(random()%100)+1.0;
double speed = 1/round(random()%100)+1.0;
//设置雪花图片出现的坐标和透明度 即控制UIView的大小和该UIView在superview中的相对位置、透明度 基准为左上角
flakeView.frame = CGRectMake(startX, -100.0, 25.0*scale, 25.0*scale);
flakeView.alpha = 0.25;
//将flakeView添加进主视图
[self.view addSubview:flakeView];
//在 Objective-C 和 Core Foundation 对象之间进行转换时,就需要使用 Bridge cast(待详细研究)
[UIView beginAnimations:nil context:(__bridge void *)(flakeView)];
//动画时常
[UIView setAnimationDuration:5*speed];
//动画结束 图片位置
flakeView.frame = CGRectMake(endX, 500.0, 25.0*scale, 25.0*scale);
//*1*动画结束时调用 清理flakeView
[UIView setAnimationDidStopSelector:@selector(onAnimationComplete:finished:context:)];
[UIView setAnimationDelegate:self];
[UIView commitAnimations];
}
-(void)onAnimationComplete:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context{
UIImageView *flakeView = (__bridge UIImageView *)(context);
[flakeView removeFromSuperview];
// NSLog(NSString stringWithFormat:@"[flakeView retainCount] = %d", [flakeView retainCount]]);
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
(3) 导入下面图片文件
下载下面图片,放入 SnowFall 文件夹内并命名为下面名称
flake.png选择: File -> Save
最后在 xCode 选择 Build and then Running(4)模拟器效果图
保留*1*处代码即动画结束后清理flake view效果为
不保留*1*处代码,效果为
本文源于网上博客教程,经过本人修改和测试。原blog地址 http://blog.sina.com.cn/s/blog_5fae23350100e1uk.html