按钮添加简单地烟花特效

这篇博客介绍如何在iOS应用中为按钮添加简单的烟花特效。通过创建和配置CAShapeLayer,结合CABasicAnimation,实现了点击按钮时从中心向外扩散的12条随机颜色的光线动画,形成类似烟花绽放的效果。


@property (nonatomic, strong) UIView *dowView;

@property (nonatomic, strong) UIButton *dowLoadButton;


/// 创建控件

 self.dowView = [[UIView alloc] initWithFrame:CGRectMake(200, 100, 100, 100)];

    [self.view addSubview:self.dowView];

//    self.dowView.backgroundColor = [UIColor lightGrayColor];

    ///

    self.dowLoadButton = [[UIButton alloc] initWithFrame:CGRectMake(25, 25, 50, 50)];

    [self.dowView addSubview:self.dowLoadButton];

    self.dowLoadButton.layer.cornerRadius = 25;

    self.dowLoadButton.layer.masksToBounds = YES;

    self.dowLoadButton.backgroundColor = [UIColor orangeColor];

    [self.dowLoadButton addTarget:self action:@selector(downloadAction) forControlEvents:UIControlEventTouchUpInside];



//// 执行方法 添加防止变态点击的方法

- (void)downloadAction{

    //先将未到时间执行前的任务取消

    [[self class] cancelPreviousPerformRequestsWithTarget:self selector:@selector(allTaskBeginDownload)object:nil];

    [self performSelector:@selector(allTaskBeginDownload)withObject:nil afterDelay:0.2f];

   }


-(void) allTaskBeginDownload{

    // button的点击事件写在这里

    CABasicAnimation *anim = [CABasicAnimation animationWithKeyPath:@"strokeStart"];

    anim.fromValue = @(0.6);/// 调整光线的起始位置 当是0时 光线从中心开始


    anim.toValue = @(1);

    anim.beginTime = CACurrentMediaTime();

    anim.repeatCount = 1;/// 重复次数

    anim.duration = 0.5; /// 动画时间

    anim.fillMode = kCAFillModeForwards;

    [anim isRemovedOnCompletion];

    /// 循环添加12条光线

    for (NSInteger i = 0; i<12; i++) {

        CGMutablePathRef path=CGPathCreateMutable();

        CGPathMoveToPoint(path, NULL, self.dowView.frame.size.width/2, self.dowView.frame.size.height/2);

        CGPathAddLineToPoint(path, NULL, self.dowView.frame.size.width/2+40(调整光线起始位置和长度)*cos(2*(M_PI)*i/12), self.dowView.frame.size.width/2+40*sin(2*M_PI*i/12));

        CAShapeLayer *trackLayer = [CAShapeLayer layer];

        //// 设置随机颜色

        trackLayer.strokeColor = [UIColor colorWithRed:(arc4random()%226)/225.0 green:(arc4random()%226)/225.0 blue:(arc4random()%226)/225.0 alpha:1].CGColor;

        /// 创建光线宽

        trackLayer.lineWidth = 1;

        trackLayer.path = path;

        trackLayer.fillColor = [UIColor clearColor].CGColor;

        trackLayer.strokeStart = 1;

        [self.dowView.layer addSublayer:trackLayer];

        [trackLayer addAnimation:anim forKey:@"strokeStart"];

    }

}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值