工程中要實現(xiàn)下圖自增長數(shù)字的效果。
實現(xiàn)的思想:從開始到本次數(shù)字跳動所花費的時間占總動畫時長的比率,通過這個比率來換算出本次數(shù)字跳動該出現(xiàn)的值招盲。
需要 CADisplayLink 來幫助實現(xiàn)。(在波浪中已經(jīng)使用過了)
構(gòu)造方法:
- (void)countFromValue:(CGFloat)fromValue toValue:(CGFloat)toValue duration:(NSTimeInterval)duration {
????? _toValue = toValue; //最大值
????? _fromValue = fromValue;? // 初始值
???? _duration = duration; // 持續(xù)時間
???? _progress = 0; // 從開始到本次數(shù)字跳動占總時間的進度
???? _lastUpdate = [NSDate timeIntervalSinceReferenceDate]; // 本次跳動的上次數(shù)字跳動
???? self.displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(updateValue:)];
???? [self.displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
}
- (void)updateValue:(CADisplayLink *)displayLink {
??????? NSTimeInterval now = [NSDate timeIntervalSinceReferenceDate];
? ? ? ? _progress += now - _lastUpdate;? // 通過每次 _progress 累加來計算總進度
??????? _lastUpdate = now;
??????? [self setTextValue:[self currentValue]];
}
- (void)setTextValue:(CGFloat)value {
??? NSString *str = [NSString stringWithFormat:@"%f",value];
??? self.text = str;
}
- (CGFloat)currentValue {
? ? if (_progress >= _duration) {? // _progress 是否大于總時長
????? return _toValue;
???? }
? ? CGFloat percent = _progress / _duration; // 累加的_progress占總時間的比率
//? ? CGFloat updateVal = powf(percent, 3.f); // 可以通過次方來加速增長
??? return _fromValue + (percent * (_toValue - _fromValue)); // 本次跳動的數(shù)字
}
?