下面是代码 直接一个类就行了
#import "ViewController.h"
@interface ViewController ()
@property (nonatomic,strong) NSTimer *timer;
@property (nonatomic,strong) UIButton *bgBUutton;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.bgBUutton = [[UIButton alloc] initWithFrame:UIScreen.mainScreen.bounds];
[self.bgBUutton addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
self.bgBUutton.backgroundColor = [UIColor whiteColor];
self.bgBUutton.userInteractionEnabled = YES;
[self.view addSubview:self.bgBUutton];
[self startRedPackets];
}
-(void)btnClick:(UIButton*)btn{
NSLog(@"点击了红包");
// [btn removeFromSuperview];
}
- (void)startRedPackets {
self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(showRain) userInfo:nil repeats:YES];
//[self.timer invalidate];
}
- (void)showRain {
CALayer*moveLayer = [CALayernew];
moveLayer.bounds=CGRectMake(0,0,80,80);//红包大小
moveLayer.anchorPoint=CGPointMake(0,0);
moveLayer.position=CGPointMake(0, -80);//红包起始位置
moveLayer.contents= (id)[UIImageimageNamed:@"ic_pan_redbag"].CGImage;
[self.bgBUutton.layeraddSublayer:moveLayer];
CAKeyframeAnimation *moveAnimation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
// 红包掉落展示的范围
NSValue *A = [NSValue valueWithCGPoint:CGPointMake(arc4random() % 414, 0)];
NSValue *B = [NSValue valueWithCGPoint:CGPointMake(arc4random() % 414, 667)];
moveAnimation.values=@[A,B];
moveAnimation.duration=arc4random() %200/100.0+5.5;//红包掉落时间
moveAnimation.repeatCount=1;
moveAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
[moveLayeraddAnimation:moveAnimationforKey:nil];
// 红包掉落时候翻转动画
CAKeyframeAnimation *transAnimation = [CAKeyframeAnimation animationWithKeyPath:@"transform"];
CATransform3D r0 = CATransform3DMakeRotation(M_PI/180 * (arc4random() % 360),0,0,-1);
CATransform3D r1 = CATransform3DMakeRotation(M_PI/180 * (arc4random() % 360),0,0,-1);
transAnimation.values = @[[NSValue valueWithCATransform3D:r0],[NSValue valueWithCATransform3D:r1]];
transAnimation.duration=arc4random() %200/100.0+3.5;
transAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
[transAnimationsetFillMode:kCAFillModeForwards];
[transAnimationsetRemovedOnCompletion:NO];
[moveLayeraddAnimation:transAnimationforKey:nil];
}
@end