zoukankan      html  css  js  c++  java
  • 猫猫学IOS(三十三)UI之Quartz2D雪花飘落效果刷帧

    猫猫分享,必须精品

    原创文章,欢迎转载。转载请注明:翟乃玉的博客
    地址:http://blog.csdn.net/u013357243?viewmode=contents

    效果:

    这里写图片描述

    可以加入随机数实现真的飘落效果哦。

    代码:

    -(id)initWithCoder:(NSCoder *)aDecoder
    {
        //请注意这里一定要先初始化父类的构造方法
        if (self=[super initWithCoder:aDecoder]) {
            NSLog(@"initWithCoder:");
    
            //NSTimer一般用于定时的更新一些非界面上的数据,告诉多久调用一次
            //使用定时器,使用该定时器会出现卡顿的现象
            //        [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(updateImage) userInfo:nil repeats:YES];
    
            // CADisplayLink刷帧,默认每秒刷新60次
            //该定时器创建之后,默认是不会执行的,需要把它加载到消息循环中
            CADisplayLink *display= [CADisplayLink displayLinkWithTarget:self selector:@selector(updateImage)];
            [display addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
    
        }
        return self;
    }
    
    -(void)updateImage
    {
        //调用该方法重绘画面
        [self setNeedsDisplay];
    }
    -(void)awakeFromNib
    {
        NSLog(@"awakeFromNib");
    }
    
    - (void)drawRect:(CGRect)rect
    {
        //把图片绘制到view上
    
        //每次调用该方法对画面进行重绘时,imageY的值就+5
        self.imageY+=5;
        //判断,当雪花超出屏幕的时候,让图片从头开始降落
        if (self.imageY>rect.size.height) {
            self.imageY=0;
        }
        UIImage *image=[UIImage imageNamed:@"snow"];
        [image drawAtPoint:CGPointMake(188, self.imageY)];
    
        UIImage *image2=[UIImage imageNamed:@"cat"];
        [image2 drawAtPoint:CGPointMake(10, self.imageY)];
    
    }

    重要说明

    (1)下面两个方法的调用顺序

    -(void)awakeFromNib

    -(id)initWithCoder:(NSCoder *)aDecoder

    提示:如果view是从xib或storyboard中创建可以调用awakefromnib方法,归档。从文件创建view,其实会先调用initwithcoder这个方法。xib和storyboard也是文件。

    上面两个方法,-(id)initWithCoder:(NSCoder *)aDecoder会先调用。实现该方法需要实现NSCoding协议,由于创建的UIView默认就已经实现了该协议。

    可以进入到头文件查看:

    这里写图片描述

    定时器

    第一个:

    [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(updateImage) userInfo:nil repeats:YES];

    说明: NSTimer一般用于定时的更新一些非界面上的数据,告诉多久调用一次

    第二个:

        CADisplayLink *display= [CADisplayLink displayLinkWithTarget:self selector:@selector(updateImage)];
    
        [display addToRunLoop:[NSRunLoopmainRunLoop] forMode:NSDefaultRunLoopMode];
    

      说明: CADisplayLink刷帧,默认每秒刷新60次。该定时器创建之后,默认是不会执行的,需要把它加载到消息循环中

  • 相关阅读:
    洛谷-P5709 【深基2.习6】Apples Prologue
    右键添加功能
    配置Java环境变量遇到的坑
    mysql安装
    页面置换算法
    程序员画图软件
    Java中传值和传引用
    计算机网络之链路层
    Python开发【第十五篇】模块的导入
    Python开发【第十四篇】装饰器
  • 原文地址:https://www.cnblogs.com/znycat/p/4521018.html
Copyright © 2011-2022 走看看