前言
前段時(shí)間在研究YYModel框架時(shí)學(xué)到不少東西,尤其是下面要講述的查看屏幕幀數(shù)的小工具.個(gè)人感覺在項(xiàng)目里比較實(shí)用,自己模仿寫了一個(gè),代碼中有詳細(xì)注釋,有需要的小伙伴們可以點(diǎn)擊這里查看, 如果star一下就更好了??, 請(qǐng)看我的效果圖??
AxeFPSLabel實(shí)現(xiàn)思路
- 首先說下CADisplayLink, CADisplayLink是一種定時(shí)器, 系統(tǒng)的每一幀刷新時(shí)都會(huì)被調(diào)用. CADisplayLink中的timestamp是系統(tǒng)每次調(diào)用時(shí)的系統(tǒng)時(shí)間戳柱衔,通過計(jì)算兩次時(shí)間戳的間隔奋蔚,可以得到每一幀所花費(fèi)的時(shí)間特纤,既可以獲取當(dāng)前每秒能刷新多少幀您单。
下面給出YYFPSLabel源碼
- YYFPSLabel.h
/**
Show Screen FPS...
The maximum fps in OSX/iOS Simulator is 60.00.
The maximum fps on iPhone is 59.97.
The maxmium fps on iPad is 60.0.
*/
@interface YYFPSLabel : UILabel
@end
- YYFPSLabel.m
#import "YYFPSLabel.h"
#import "YYWeakProxy.h"
#define kSize CGSizeMake(55, 20)
@implementation YYFPSLabel {
CADisplayLink *_link;
NSUInteger _count;
NSTimeInterval _lastTime;
UIFont *_font;
UIFont *_subFont;
NSTimeInterval _llll;
}
- (instancetype)initWithFrame:(CGRect)frame {
if (frame.size.width == 0 && frame.size.height == 0) {
frame.size = kSize;
}
self = [super initWithFrame:frame];
self.layer.cornerRadius = 5;
self.clipsToBounds = YES;
self.textAlignment = NSTextAlignmentCenter;
self.userInteractionEnabled = NO;
self.backgroundColor = [UIColor colorWithWhite:0.000 alpha:0.700];
_font = [UIFont fontWithName:@"Menlo" size:14];
if (_font) {
_subFont = [UIFont fontWithName:@"Menlo" size:4];
} else {
_font = [UIFont fontWithName:@"Courier" size:14];
_subFont = [UIFont fontWithName:@"Courier" size:4];
}
// 如果直接用 self 或者 weakSelf,都不能解決循環(huán)引用問題
_link = [CADisplayLink displayLinkWithTarget:[YYWeakProxy proxyWithTarget:self] selector:@selector(tick:)];
// __weak typeof(self) weakSelf = self;
// _link = [CADisplayLink displayLinkWithTarget:weakSelf selector:@selector(tick:)];
[_link addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];
return self;
}
- (void)dealloc {
[_link invalidate];
NSLog(@"timer release");
}
- (CGSize)sizeThatFits:(CGSize)size {
return kSize;
}
- (void)tick:(CADisplayLink *)link {
if (_lastTime == 0) {
_lastTime = link.timestamp;
return;
}
_count++;
NSTimeInterval delta = link.timestamp - _lastTime;
if (delta < 1) return;
_lastTime = link.timestamp;
float fps = _count / delta;
_count = 0;
CGFloat progress = fps / 60.0;
UIColor *color = [UIColor colorWithHue:0.27 * (progress - 0.2) saturation:1 brightness:0.9 alpha:1];
NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%d FPS",(int)round(fps)]];
[text addAttribute:NSForegroundColorAttributeName value:color range:NSMakeRange(0, text.length - 3)];
[text addAttribute:NSForegroundColorAttributeName value:[UIColor whiteColor] range:NSMakeRange(text.length - 3, 3)];
[text addAttribute:NSFontAttributeName value:_font range:NSMakeRange(0, text.length)];
[text addAttribute:NSFontAttributeName value:_subFont range:NSMakeRange(text.length - 4, 1)];
self.attributedText = text;
}
后續(xù)
- 閑下來的時(shí)候會(huì)繼續(xù)完善補(bǔ)充文章,各位小伙伴有什么見解或是疑問可以留言給我,歡迎討論??!