美文网首页
浅析CADisplayLink

浅析CADisplayLink

作者: Z了个L | 来源:发表于2017-01-22 20:09 被阅读18次
    • 定时器有2种,一种是NSTimer,一种是CADisplayLink,今天笔者就看看CADisplayLink怎么去使用

    • 初始化界面效果图:

    • 主要代码:
    // ViewController.h
    #import <UIKit/UIKit.h>
    
    @interface ViewController : UIViewController
    
    
    @end
    
    
    // ViewController.m
    #import "ViewController.h"
    
    @interface ViewController ()
    
    @end
    
    @implementation ViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
    
    }
    
    @end
    
    // VCView.h
    #import <UIKit/UIKit.h>
    
    @interface VCView : UIView
    
    @end
    
    // VCView.m
    #import "VCView.h"
    
    @implementation VCView
    
    - (void)awakeFromNib {
    
        // 添加定时器
        // [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(update) userInfo:nil repeats:YES];
    
        // 什么时候调用指定的方法?
        // 当下一次屏幕刷新时调用(屏幕每一秒刷新60)
        CADisplayLink *link = [CADisplayLink displayLinkWithTarget:self selector:@selector(update)];
    
        // 想要让CADisplayLink工作, 必须得要添加到主运行循环当中.
        [link addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
    
        // setNeedsDisplay底层会调用drawRect,并不是立马调用的.只是设了一个调用的标志.
        // 等下一次屏幕刷新时才去调用drawRect
    }
    
    static int _snowY = 0;
    - (void)update {
        NSLog(@"%s",__func__);
        _snowY += 10;
        if (_snowY > self.bounds.size.height) {
            _snowY = 0;
        }
        // 重绘
        [self setNeedsDisplay];
    }
    
    
    - (void)drawRect:(CGRect)rect {
        //加载图片
        UIImage *image = [UIImage imageNamed:@"雪花"];
        [image drawAtPoint:CGPointMake(0, _snowY)];
    }
    
    
    @end
    
    
    • 简单效果图:

    相关文章

      网友评论

          本文标题:浅析CADisplayLink

          本文链接:https://www.haomeiwen.com/subject/jgpobttx.html