雪花降落CADisplayLink

时间:2023-03-09 09:36:22
雪花降落CADisplayLink

p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 18.0px "PingFang SC"; color: #1d9421 }
p.p2 { margin: 0.0px 0.0px 0.0px 0.0px; font: 18.0px Menlo }
p.p3 { margin: 0.0px 0.0px 0.0px 0.0px; font: 18.0px Menlo; min-height: 21.0px }
p.p4 { margin: 0.0px 0.0px 0.0px 0.0px; font: 18.0px Menlo; color: #1d9421 }
p.p5 { margin: 0.0px 0.0px 0.0px 0.0px; font: 18.0px Menlo; color: #3d1d81 }
span.s1 { font: 18.0px Menlo }
span.s2 { }
span.s3 { color: #c32275 }
span.s4 { color: #000000 }
span.s5 { font: 18.0px "PingFang SC" }
span.s6 { color: #6122ae }
span.s7 { color: #3d1d81 }
span.s8 { font: 18.0px Menlo; color: #000000 }
span.s9 { color: #703daa }
span.s10 { color: #0435ff }
span.s11 { color: #539aa4 }
span.s12 { color: #294c50 }
span.s13 { color: #78492a }

//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];

}];

}