YYFPSLabel.m 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. //
  2. // YYFPSLabel.m
  3. // YYKitExample
  4. //
  5. // Created by ibireme on 15/9/3.
  6. // Copyright (c) 2015 ibireme. All rights reserved.
  7. //
  8. #import "YYFPSLabel.h"
  9. #import "YYWeakProxy.h"
  10. #define kSize CGSizeMake(55, 20)
  11. @implementation YYFPSLabel {
  12. CADisplayLink *_link;
  13. NSUInteger _count;
  14. NSTimeInterval _lastTime;
  15. UIFont *_font;
  16. UIFont *_subFont;
  17. NSTimeInterval _llll;
  18. }
  19. - (instancetype)initWithFrame:(CGRect)frame {
  20. if (frame.size.width == 0 && frame.size.height == 0) {
  21. frame.size = kSize;
  22. }
  23. self = [super initWithFrame:frame];
  24. self.layer.cornerRadius = 5;
  25. self.clipsToBounds = YES;
  26. self.textAlignment = NSTextAlignmentCenter;
  27. self.userInteractionEnabled = NO;
  28. self.backgroundColor = [UIColor colorWithWhite:0.000 alpha:0.700];
  29. _font = [UIFont fontWithName:@"Menlo" size:14];
  30. if (_font) {
  31. _subFont = [UIFont fontWithName:@"Menlo" size:4];
  32. } else {
  33. _font = [UIFont fontWithName:@"Courier" size:14];
  34. _subFont = [UIFont fontWithName:@"Courier" size:4];
  35. }
  36. _link = [CADisplayLink displayLinkWithTarget:[YYWeakProxy proxyWithTarget:self] selector:@selector(tick:)];
  37. [_link addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];
  38. return self;
  39. }
  40. - (void)dealloc {
  41. [_link invalidate];
  42. }
  43. - (CGSize)sizeThatFits:(CGSize)size {
  44. return kSize;
  45. }
  46. - (void)tick:(CADisplayLink *)link {
  47. if (_lastTime == 0) {
  48. _lastTime = link.timestamp;
  49. return;
  50. }
  51. _count++;
  52. NSTimeInterval delta = link.timestamp - _lastTime;
  53. if (delta < 1) return;
  54. _lastTime = link.timestamp;
  55. float fps = _count / delta;
  56. _count = 0;
  57. CGFloat progress = fps / 60.0;
  58. // UIColor *color = [UIColor colorWithHue:0.27 * (progress - 0.2) saturation:1 brightness:0.9 alpha:1];
  59. NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%d FPS",(int)round(fps)]];
  60. // [text setColor:color range:NSMakeRange(0, text.length - 3)];
  61. // [text setColor:[UIColor whiteColor] range:NSMakeRange(text.length - 3, 3)];
  62. // text.font = _font;
  63. // [text setFont:_subFont range:NSMakeRange(text.length - 4, 1)];
  64. self.attributedText = text;
  65. }
  66. @end