- NSTimer CADisplayLink
? 通過(guò) NSTimer 實(shí)現(xiàn)的動(dòng)畫(huà)可能造成卡頓、不連貫的情況(NSTimer 不準(zhǔn)確)
? CADisplayLink 表示"顯示連接", 與顯示器的刷新頻率相關(guān)。
? 顯示器每秒鐘刷新60次(60HZ)(電視新聞上拍的電腦顯示器就不清楚,原因刷新頻率不一樣)
? 通過(guò) CADisplayLink 來(lái)解決
/** 參考代碼:
// 核心代碼
CADisplayLink *timer = [CADisplayLink displayLinkWithTarget:self selector:@selector(moveSecond)];
[timer addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
- (void)viewDidLoad {
[super viewDidLoad];
// 1. 創(chuàng)建表盤(pán)
UIView *clockView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 150, 150)];
clockView.backgroundColor = [UIColor blueColor];
clockView.center = CGPointMake(self.view.bounds.size.width * 0.5, self.view.bounds.size.height * 0.5);
[self.view addSubview:clockView];
self.clockView = clockView;
// 2. 創(chuàng)建秒針
UIView *secondView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 5, 50)];
secondView.backgroundColor = [UIColor redColor];
secondView.layer.anchorPoint = CGPointMake(0.5, 1);
secondView.center = clockView.center;
[self.view addSubview:secondView];
self.secondView = secondView;
[self moveSecond];
// 3. 啟動(dòng)一個(gè)計(jì)時(shí)器, 每隔一秒鐘計(jì)算一下當(dāng)前秒針的位置, 然后做一次哦旋轉(zhuǎn)操作
// [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(moveSecond) userInfo:nil repeats:YES];
CADisplayLink *timer = [CADisplayLink displayLinkWithTarget:self selector:@selector(moveSecond)];
[timer addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
}
- (void)moveSecond
{
// 1. 計(jì)算當(dāng)前的秒數(shù)
NSDate *nowDate = [NSDate date];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSInteger seconds = [calendar component:NSCalendarUnitSecond fromDate:nowDate];
// 2. 計(jì)算每一秒的弧度
CGFloat rotation = M_PI * 2 / 60;
// 3. 用每一秒的弧度 * 秒數(shù) , 計(jì)算出本次要旋轉(zhuǎn)的弧度
rotation = seconds * rotation;
// 4. 旋轉(zhuǎn)秒針
self.secondView.transform = CGAffineTransformMakeRotation(rotation);
}
// 每次觸摸一次屏幕秒針轉(zhuǎn)一次
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
CGFloat rotation = M_PI * 2 / 60;
self.secondView.transform = CGAffineTransformRotate(self.secondView.transform, rotation);
}
@end
*/
- 當(dāng)雙擊 home 鍵的時(shí)候, 動(dòng)畫(huà)不會(huì)暫停
- 注意: 如果當(dāng)動(dòng)畫(huà)正在執(zhí)行的時(shí)候, 將程序退出到后臺(tái), 那么當(dāng)程序再次進(jìn)入前臺(tái)的時(shí)候就不執(zhí)行了。
- 原因: 因?yàn)樵俅芜M(jìn)入前臺(tái)后動(dòng)畫(huà)已經(jīng)被刪除了。
- 解決1: anim.removedOnCompletion = NO;
- 問(wèn)題: 當(dāng)雙擊 home 鍵的時(shí)候, 動(dòng)畫(huà)不會(huì)暫停。
- 解決:
/** 參考:
// 暫停
- (void)applicationWillResignActive:(UIApplication *)application {
ViewController *vc = (ViewController *)self.window.rootViewController;
[vc pause];
}
// 恢復(fù)
- (void)applicationDidBecomeActive:(UIApplication *)application {
ViewController *vc = (ViewController *)self.window.rootViewController;
[vc resume];
}
*/
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。