本教程引導讀者從零開始建立一個「下雪」動畫應用,涵蓋 UIImageView 動態建立、NSTimer 定時觸發、UIView 區塊動畫、隨機屬性生成、動畫完成回呼清理記憶體等核心 iOS 開發技能。適合初学者快速上手視圖動畫與定時器機制。
SnowFallflake.png (建議 25x25 px、透明背景 PNG),拖入專案並勾選 Copy items if needed#import
@interface MainViewController : UIViewController {
UIImage *flakeImage;
}
@property (nonatomic, retain) UIImage *flakeImage;
- (void)onTimer;
- (void)onAnimationComplete:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context;
@end
#import "MainViewController.h"
@implementation MainViewController
@synthesize flakeImage;
- (void)viewDidLoad {
[super viewDidLoad];
// 冷色調背景營造冬日氛圍
self.view.backgroundColor = [UIColor colorWithRed:0.5 green:0.5 blue:1.0 alpha:1.0];
// 載入雪花圖片 (僅載入一次,重複使用)
flakeImage = [UIImage imageNamed:@"flake.png"];
// 每秒 20 次 (0.05 秒) 產生一片雪花
[NSTimer scheduledTimerWithTimeInterval:0.05
target:self
selector:@selector(onTimer)
userInfo:nil
repeats:YES];
}
// 定時器觸發:建立並啟動單片雪花動畫
- (void)onTimer {
// 1. 建立雪花 UIImageView
UIImageView *flakeView = [[UIImageView alloc] initWithImage:flakeImage];
// 2. 隨機屬性:起始/結束 X 座標、縮放比例、下落速度
int startX = round(random() % 320);
int endX = round(random() % 320);
double scale = 1.0 / round(random() % 100) + 1.0; // 1.01 ~ 2.0
double speed = 1.0 / round(random() % 100) + 1.0; // 1.01 ~ 2.0
// 3. 設定初始幀:螢幕上方外、隨機寬度
flakeView.frame = CGRectMake(startX, -100.0, 25.0 * scale, 25.0 * scale);
flakeView.alpha = 0.25; // 半透明增加層次感
// 4. 加入視圖階層
[self.view addSubview:flakeView];
// 5. 區塊動畫:下落至螢幕底部
[UIView beginAnimations:nil context:flakeView];
[UIView setAnimationDuration:5.0 * speed]; // 5~10 秒下落
[UIView setAnimationDidStopSelector:@selector(onAnimationComplete:finished:context:)];
[UIView setAnimationDelegate:self];
// 目標幀:隨機 X、螢幕底部 (y=500)
flakeView.frame = CGRectMake(endX, 500.0, 25.0 * scale, 25.0 * scale);
[UIView commitAnimations];
}
// 動畫完成回呼:清理雪花視圖,防止記憶體洩漏
- (void)onAnimationComplete:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context {
UIImageView *flakeView = (UIImageView *)context;
[flakeView removeFromSuperview];
// 手動釋放 (非 ARC 環境)
[flakeView release];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
- (void)dealloc {
[flakeImage release];
[super dealloc];
}
@end
// 預設模式 (NSDefaultRunLoopMode) 在滑動 ScrollView 時會暫停
// 若需滑動時也持續產生雪花,請使用 NSRunLoopCommonModes
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
原始碼使用 random() % 100 有模數偏差,建議改用 arc4random_uniform(100):
double scale = 1.0 / (arc4random_uniform(100) + 1) + 1.0;
context 參數傳遞 flakeView 指標,回呼中取出並 removeFromSuperview + releaserelease,改用 __weak 避免循環引用@autoreleasepool 包裹 onTimer 內容UIImageView 循環重用,避免頻繁 alloc/freeCALayer 更輕量[UIView animateWithDuration:5.0 * speed
animations:^{
flakeView.frame = CGRectMake(endX, 500.0, 25.0 * scale, 25.0 * scale);
}
completion:^(BOOL finished) {
[flakeView removeFromSuperview];
}];
endX = startX + windOffset,風向隨時間緩慢變化flakeView.transform = CGAffineTransformMakeRotation(angle)UITouch 位置產生局部雪花爆發