雪花降落CADisplayLink

 

//CADisplayLink  和屏幕刷新频率相同

 

//开始下雪

- (void) beginShow{

    

    //启动定时器,使得一直调用setNeedsDisplay从而调用- (void) drawRect:(CGRect )rect

    //不得手动调用- (void) drawRect:(CGRect )rect

    CADisplayLink *link = [CADisplayLink displayLinkWithTarget:self selector:@selector(setNeedsDisplay)];

    //让定时器循环调用

    [link addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];

}

 

- (void) drawRect:(CGRect)rect {

    

    //控制雪花最多的个数

    //    if (self.subviews.count >250) {

    //        return;

    //    }

    if (self.subviews.count >20) {

        return;

    }

    //雪花的宽度

    int width = arc4random() % 5;

    while (width < 2) {

        width = arc4random() % 5;

    }

    //雪花的速度

    int speed = arc4random() % 10;

    while (speed < 5) {

        speed = arc4random() % 10;

    }

    

    //雪花起点y

    int startY = - (arc4random() % 100);

    //雪花起点x

    int startX = arc4random() % (int) [UIScreen mainScreen].bounds.size.width;

    //雪花终点x

    int endX = arc4random() % (int) [UIScreen mainScreen].bounds.size.width;

    //int endX = arc4random() % (int)_bgView.height;

    //int endX = arc4random() % (int)(_bgView.height - 71*GOP_HeightR);//

    

    

    

    

    UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:self.snowImgName]];

    imageView.frame = CGRectMake(startX, startY, width, width);

    [self addSubview:imageView];

    

    

    //设置动画

    [UIView animateWithDuration:speed animations:^{

        //设置雪花最终的frame

        //        imageView.frame = CGRectMake(endX, [UIScreen mainScreen].bounds.size.height, width, width);

        //雪花最终下落的高度为_bgView的高度减去71*GOP_HeightR的高度

        imageView.frame = CGRectMake(endX, _bgView.height-71*GOP_HeightR, width, width);

        

        //设置雪花的旋转

        imageView.transform = CGAffineTransformRotate(imageView.transform, M_PI);

        //设置雪花透明度,使得雪花快落地的时候就像快消失的一样

        //imageView.alpha = 0.3;

    } completion:^(BOOL finished) {

        [imageView removeFromSuperview];

    }];

    

    

}

posted @ 2017-01-03 20:24  Da雪山  阅读(246)  评论(0编辑  收藏  举报