单军华
2018-05-04 25f409185a53e5e7beb17518a684298d92d31b3f
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
//
//  BAFPSLabel.m
//  Pods
//
//  Created by HyanCat on 16/4/4.
//
//
 
#import "BAFPSLabel.h"
//#import <Masonry/Masonry.h>
 
#define IOS8_OR_LATER ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
 
@interface BAFPSLabel ()
{
    NSUInteger _tickCount;
}
@property (nonatomic, strong) CADisplayLink *displayLink;
@property (nonatomic, assign) CFTimeInterval lastTime;
@property (nonatomic, assign) NSUInteger fps;
 
@end
 
@implementation BAFPSLabel
 
+ (instancetype)showInWindow:(UIWindow *)window
{
    BAFPSLabel *label = [[BAFPSLabel alloc] initWithFrame:CGRectZero];
    label.layer.cornerRadius = 4.f;
    label.layer.masksToBounds = YES;
    label.textAlignment = NSTextAlignmentCenter;
    label.userInteractionEnabled = NO;
    label.font = [UIFont fontWithName:@"Menlo" size:12];
    
    [window addSubview:label];
    
    label.translatesAutoresizingMaskIntoConstraints = NO;
    
    NSLayoutConstraint *leadingLayout =[NSLayoutConstraint constraintWithItem:label
                                                                    attribute:NSLayoutAttributeLeading
                                                                    relatedBy:NSLayoutRelationEqual
                                                                       toItem:window
                                                                    attribute:NSLayoutAttributeLeading
                                                                   multiplier:1
                                                                     constant:10.f];
    NSLayoutConstraint *bottomLayout = [NSLayoutConstraint constraintWithItem:label
                                                                    attribute:NSLayoutAttributeBottom
                                                                    relatedBy:NSLayoutRelationEqual
                                                                       toItem:window
                                                                    attribute:NSLayoutAttributeBottom
                                                                   multiplier:1
                                                                     constant:-10.f];
    NSLayoutConstraint *widthLayout = [NSLayoutConstraint constraintWithItem:label
                                                                   attribute:NSLayoutAttributeWidth
                                                                   relatedBy:NSLayoutRelationEqual
                                                                      toItem:nil
                                                                   attribute:NSLayoutAttributeNotAnAttribute
                                                                  multiplier:0
                                                                    constant:60.f];
    NSLayoutConstraint *heightLayout = [NSLayoutConstraint constraintWithItem:label
                                                                    attribute:NSLayoutAttributeHeight
                                                                    relatedBy:NSLayoutRelationEqual
                                                                       toItem:nil
                                                                    attribute:NSLayoutAttributeNotAnAttribute
                                                                   multiplier:0
                                                                     constant:20.f];
    if (IOS8_OR_LATER) {
        [NSLayoutConstraint activateConstraints:@[leadingLayout, bottomLayout, widthLayout, heightLayout]];
    }
    else {
        [window addConstraints:@[leadingLayout, bottomLayout, widthLayout, heightLayout]];
    }
    
    return label;
}
 
- (void)dealloc
{
    [_displayLink invalidate];
}
 
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        _displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(tick:)];
        [_displayLink addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];
        _autoHide = NO;
        
        [self addObserver:self forKeyPath:NSStringFromSelector(@selector(fps)) options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:NULL];
    }
    return self;
}
 
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context
{
    if (object == self && [keyPath isEqualToString:NSStringFromSelector(@selector(fps))]) {
        NSUInteger oldFps = [[change valueForKey:NSKeyValueChangeOldKey] unsignedIntegerValue];
        NSUInteger newFps = [[change valueForKey:NSKeyValueChangeNewKey] unsignedIntegerValue];
        if (oldFps != newFps) {
            [self _displayFPS];
        }
    }
}
 
- (void)tick:(CADisplayLink *)displayLink
{
    CFTimeInterval currentTime = displayLink.timestamp;
    if (_lastTime == 0) {
        // first time.
        _lastTime = currentTime;
        return;
    }
    _tickCount++;
    CFTimeInterval delta = currentTime - _lastTime;
    if (delta < 1) return;
    // get fps
    self.fps = MIN(lrint(_tickCount / delta), 60);
    _tickCount = 0;
    _lastTime = currentTime;
}
 
- (void)fadeOut
{
    CATransition *fadeTransition = [CATransition animation];
    [self.layer addAnimation:fadeTransition forKey:kCATransition];
    [self setAttributedText:nil];
    self.layer.backgroundColor = nil;
}
 
- (void)_displayFPS
{
    if (self.attributedText == nil) {
        // fade in
        CATransition *fadeTransition = [CATransition animation];
        [self.layer addAnimation:fadeTransition forKey:kCATransition];
    }
    
    CGFloat hue = self.fps > 24 ? (self.fps - 24) / 120.f : 0;
    self.textColor = [UIColor colorWithHue:hue saturation:1 brightness:0.9 alpha:1];
    self.text = [NSString stringWithFormat:@"%@ FPS", @(self.fps)];
    self.layer.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.7f].CGColor;
    
    if (self.autoHide) {
        [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(fadeOut) object:nil];
        [self performSelector:@selector(fadeOut) withObject:nil afterDelay:2];
    }
}
 
@end