屏幕监测帧率如何实现
A CADisplayLink object is a timer object that allows your application to synchronize its drawing to the refresh rate of the display.这是官方文档对于CADisplayLink的定义,意思就是说CADisplayLink是一个定时器(但并不继承自NSTimer),它能够让你的应用以屏幕刷新的帧率来同步更新UI,所以我们可以通过它1s内调用指定target的指定方法的次数来获得屏幕刷新的帧率,从而来判断CPU的运行状态。
使用
-(BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions{[CPUFpsLabel setupOnView:[[application windows]firstObject].rootViewController.view];returnYES;}
CPUFpsLabel
@interface CPUFpsLabel: UILabel
+(void)setupOnView:(UIView*)view;
-(void)start;
@end
@implementation CPUFpsLabel {
CADisplayLink*_link;
NSUInteger _count;
NSTimeInterval _lastTime;
}
+(void)setupOnView:(UIView*)view{
CGSize screenSize=[UIScreen mainScreen].bounds.size;
CPUFpsLabel*fpsLabel=[[CPUFpsLabel alloc]initWithFrame:CGRectMake(screenSize.width/2.0+25,0,50,20)];
[fpsLabel start];
[view addSubview:fpsLabel];
}
-(instancetype)initWithFrame:(CGRect)frame{
self=[superinitWithFrame:frame];
if(self){self.font=[UIFont boldSystemFontOfSize:12];
self.textColor=[UIColor colorWithRed:0.33green:0.84blue:0.43alpha:1.00];
self.backgroundColor=[UIColor clearColor];
self.textAlignment=NSTextAlignmentCenter;
_link=[CADisplayLink displayLinkWithTarget:selfselector:@selector(tick:)];
[_link addToRunLoop:[NSRunLoop mainRunLoop]forMode:NSRunLoopCommonModes];
_link.paused=YES;
[[NSNotificationCenter defaultCenter]addObserver:selfselector:@selector(applicationDidBecomeActiveNotification) name:UIApplicationDidBecomeActiveNotification object:nil];
[[NSNotificationCenter defaultCenter]addObserver:selfselector:@selector(applicationWillResignActiveNotification)name:UIAppli cationWillResignActiveNotification object:nil];
}
returnself;
}
- (void)dealloc{
[_link invalidate];
[_link removeFromRunLoop:[NSRunLoop mainRunLoop]forMode:NSRunLoopCommonModes];
}
- (void)applicationDidBecomeActiveNotification{
[_link setPaused:NO];
}
- (void)applicationWillResignActiveNotification{
[_link setPaused:YES];
}
- (void)start {
[_link setPaused:NO];
}
- (void)tick:(CADisplayLink*)link{
if(_lastTime==0){
_lastTime=link.timestamp;
return;
}
_count++;
NSTimeInterval delta=link.timestamp-_lastTime;
if(delta<1)return;
_lastTime=link.timestamp;
floatfps=_count/delta;
_count=0;
NSString*fpsString=[NSString stringWithFormat:@"%zd fps",(int)round(fps)];
self.text=fpsString;
}
@end