CADisplayLink是個什麼鬼???

最近看開源代碼總是看到CADisplayLink,這個一般用在須要不停繪製頁面的狀況下,既然是QuatzCore框架中的,那繪製什麼的效率確定應該比用Timer高了吧.... 框架

用法和NSTimer很像。oop

    CADisplayLink *dl = [CADisplayLink displayLinkWithTarget:self selector:@selector(timeCallback:)];
    [dl addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];
    self.displayLink = dl;
    
    UILabel *lab = [[UILabel alloc] initWithFrame:CGRectMake(20, 80, 200, 50)];
    lab.backgroundColor = [UIColor blueColor];
    [self.view addSubview:lab];
    lab.textColor = [UIColor redColor];
    
    lab.font = [UIFont systemFontOfSize:28];
    lab.text = [NSString stringWithFormat:@"倒計時%ds", i];
    _textLabel = lab;

下面是回調測試

- (void)timeCallback:(id)sender {
    
    int second = i--;
    NSString *str = [NSString stringWithFormat:@"倒計時%ds", second];
    [self.textLabel setText:str];
    
    CFTimeInterval time = self.displayLink.duration;
    NSLog(@"%f", time);                   // 0.01666666...
    
    NSLog(@"%ld", self.displayLink.frameInterval);
    int y = round(1.0/time);
    
    self.displayLink.frameInterval = y;   //  約等於60幀,其實就是60啦
    NSLog(@"%ld", self.displayLink.frameInterval);
    
}

固然不用的時候記得atom

- (void)removeFromRunLoop:(NSRunLoop *)runloop forMode:(NSString *)mode;
或者
- (void)invalidate;
@property(readonly, nonatomic) CFTimeInterval timestamp;   // 當前時間
@property(readonly, nonatomic) CFTimeInterval duration;    // 每幀的間隔

  

測試結果是1/60 s調用一次callback。code

相關文章
相關標籤/搜索