天天省钱快报

YYFPSLabel.m 2.3KB

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