【iOS】点赞动画(UIView动画 帧动画 粒子动画)

3,979 阅读6分钟

前言

今天来写一下项目里用到的一个点赞效果吧,最主要的也就是这个粒子动画了,打算自己写一个,因为参考了几个文章没有发现封装的比较现成的代码,最终的效果图看一下:
点赞动画.gif

这个gif展示出来的效果跟真机或者模拟器显示的还是有差异的,在模拟器和真机上运行动画很流畅(LICEcap最近出了问题所以没用,凑合使用了QQ上的录屏功能)

思路

  • 选用控件:

有点击事件,有图片有数字,有状态,UIButton最好

  • 动画拆分:

1.粒子动画的粒子生成,之后扩散,到达一定位置后消失 (粒子动画) 2.上边+1数字,渐变出现,达到一定y值时隐藏 (UIView动画或帧动画) 3.右边的点赞数字,由0隐藏,透明度渐变出现,变为红色 (UIView动画或帧动画) 4.按钮由灰变红就不用说了,设置按钮图片就好

  • 注意点:

连续点击可能出现的网络请求问题( 点赞/取消点赞操作网络延迟问题 )

具体实现

一 . 粒子动画

    //1.创建一个能放射粒子的cell(粒子源)
    CAEmitterCell * explosionCell = [CAEmitterCell emitterCell];
    //透明度变化速度
    explosionCell.alphaSpeed = -1.0;
    //透明度变化范围
    explosionCell.alphaRange = 0.5;
    //粒子存在时间
    explosionCell.lifetime = 0.5;
    //粒子存在时间的范围
    explosionCell.lifetimeRange = 0.2;
    //每个cell可以释放多少个粒子
    explosionCell.birthRate = 15;
    //粒子扩散的速度
    explosionCell.velocity = 75.f;
    //粒子扩散的速度上下区间 +10 or -10
    //    explosionCell.velocityRange = 10.f;
    //最大 - M_PI_4/2  粒子发射方向
    explosionCell.emissionLongitude = - M_PI_2;
    explosionCell.emissionRange = M_PI_2;
    //粒子形变大小
    explosionCell.scale = 0.08;
    //形变范围
    //    explosionCell.scaleRange = 0.02;
    //粒子内容
    explosionCell.contents = (id)[[UIImage imageNamed:@"spark_red"] CGImage];
    //粒子初始颜色
//    explosionCell.color = [UIColor yellowColor].CGColor;
    explosionCell.color = [UIColor redColor].CGColor;
    //粒子其他混合颜色
    explosionCell.redRange = 10;
    explosionCell.greenRange = 10;
    explosionCell.blueRange = 10;
    //混合色颜色变化速度
    explosionCell.redSpeed = 10;
    explosionCell.greenSpeed = 10;
    explosionCell.blueSpeed = 10;
    
    
    // 2.发射源
    CAEmitterLayer * explosionLayer = [CAEmitterLayer layer];
    [self.layer addSublayer:explosionLayer];
    self.explosionLayer = explosionLayer;
    //发射位置 - 粒子从哪里出现开始扩散
    //self.explosionLayer.emitterSize = CGSizeMake(self.bounds.size.width + 3, self.bounds.size.height + 3);
    //发射源的形状
    explosionLayer.emitterShape = kCAEmitterLayerPoint;
    //每秒发射cell的数量
    explosionLayer.birthRate = 0;
    //发射模式: 从发射体的哪个位置发出粒子: 某个点,表面,边缘,内部
    explosionLayer.emitterMode = kCAEmitterLayerVolume;
    //粒子的渲染模式
    explosionLayer.renderMode = kCAEmitterLayerAdditive;
    
    explosionLayer.emitterCells = @[explosionCell];

1.粒子动画的核心就是这些代码了,创建释放粒子的粒子源cell,由发射源发射这些粒子源cell,这些cell扩散出粒子,形成粒子动画

2.在创建粒子源cell后设置的属性,有的是关于粒子源本身,有的是关于扩散出来的粒子,其中带有Range的属性,这个是上下浮动的范围值,即区间,例如粒子的生命周期lifetime = 0.5,设置lifetimeRange = 0.2,那么粒子真正的生命周期是0.3 ~ 0.7,即粒子真正的生命周期是0.3 ~ 0.7的随机值,随机值的属性多了,就形成了无规则的动画

  1. emissionLongitude = - M_PI_2 代表垂直向上的方向

二 . 拳头动画

拳头的放大效果用帧动画实现,animation.keyPath = @"transform.scale"

/**
 *  拳头放大动画
 */
- (void)enlargementAnimation {
    
    //通过键帧动画实现缩放
    CAKeyframeAnimation * animation = [CAKeyframeAnimation animation];
    animation.keyPath = @"transform.scale";
    animation.values = @[@1.5,@2.0,@3.5];
    animation.duration = 0.25;
    animation.calculationMode = kCAAnimationCubic;
    self.backImageView.alpha = 0.05;
    [self.backImageView.layer addAnimation:animation forKey:nil];
    
}

三.两个数字动画

- (void)countAnimation {
    
    //1.添加数字+1透明度动画
    CAKeyframeAnimation *animation0 = [CAKeyframeAnimation animation];
    animation0.keyPath = @"opacity";
    animation0.values = @[@0.5,@0.8,@1.0];
    animation0.duration = 0.5;
    animation0.calculationMode = kCAAnimationCubic;
    [self.incLabel.layer addAnimation:animation0 forKey:nil];
    //开始动画时"+1"上升label回到起始位置
    self.incLabel.y = _incOrginY;
    //防止label闪烁
    self.incLabel.alpha = 1;
    
    //2.添加"+1"慢慢变大动画
    CAKeyframeAnimation *animationScale = [CAKeyframeAnimation animation];
    animationScale.keyPath = @"transform.scale";
    animationScale.values = @[@1.0,@1.1,@1.2];
    animationScale.duration = 1.0;
    animationScale.calculationMode = kCAAnimationCubic;
    [self.incLabel.layer addAnimation:animationScale forKey:nil];
    
    //3.添加"+1"s向上位移动画
    __weak typeof(self) weakSelf = self;
    [UIView animateWithDuration:0.5 delay:0.0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        
        weakSelf.incLabel.y = self->_incOrginY - 18;
        
    } completion:^(BOOL finished) {
        //4.添加"+1"慢慢消失动画
        CAKeyframeAnimation *animation2 = [CAKeyframeAnimation animation];
        animation2.keyPath = @"opacity";
        animation2.values = @[@0.8,@0.5,@0];
        animation2.duration = 0.5;
        animation2.calculationMode = kCAAnimationCubic;
        [weakSelf.incLabel.layer addAnimation:animation2 forKey:nil];
        self.incLabel.alpha = 0;
    }];
}

使用

  • demo地址在文章末尾
  • 使用相对比较简单一些,导入头文件,创建button,设置button的Action即可
#import "RBCLikeButton.h"
//1.创建点赞按钮
RBCLikeButton *likeBtn = [[RBCLikeButton alloc] initWithFrame:CGRectMake(130, 200, 100, 100)];
[likeBtn setImage:[UIImage imageNamed:@"day_like"] forState:UIControlStateNormal];
[likeBtn setImage:[UIImage imageNamed:@"day_like_red"] forState:UIControlStateSelected];
[likeBtn addTarget:self action:@selector(likeBtnClickAction:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:likeBtn];

  • 点赞对应的Action,代码稍微长了一点点,不过是附带网络请求和网络请求不同状况作出的处理操作,具体的解释代码里面全部包含了
//点赞/取消点赞操作
- (void)likeBtnClickAction:(RBCLikeButton *)btn {
    
    //1.记录是否是点赞操作
    BOOL isThump = !btn.isSelected;
    
    //2.点赞量,正式运用中可自定义(从服务器获取当前的点赞量)
    NSInteger num = btn.thumpNum;
    
    //3.计算点赞后数值
    if (isThump) {
        num = num + 1;//点赞后的点赞数
    }else{
        num = num - 1;//取消点赞后的点赞数
    }
    
    //4.调用点赞动画,设置点赞button的点赞数值
    [btn setThumbWithSelected:isThump thumbNum:num animation:YES];
    
    //5.网络请求
    if (isThump) {//如果是点赞操作
        
        //发起网络请求,告知服务器APP进行了点赞操作,服务器的返回结果为isRequestSuccess
        
        BOOL isRequestSuccess = YES;//请求成功
        
        if (!isRequestSuccess) {//如果操作失败(没有网络或接口异常)
            
            //取消刚才的点赞操作导致的数值变换和点赞按钮的状态变化
            [btn cancelLike];
        }
    }else{//如果是取消点赞操作
        
        //发起网络请求,告知服务器APP进行了取消点赞操作,服务器的返回结果为isRequestSuccess
        
        BOOL isRequestSuccess = NO;//请求失败
        
        if (!isRequestSuccess) {//如果操作失败(没有网络或接口异常)
            
            //恢复到点赞之前的点赞数值和点赞按钮的状态变化
            [btn recoverLike];
        }
    }
}

为什么先改变本地按钮的状态,然后再网络请求呢?

  • 之所以这么做是为了用户体验考虑,直观的展现给他操作的结果,不让他发觉感觉不到的网络请求(因为可能存在网络延迟的情况)
  • 我们也准备了网络请求失败的补救方法recoverLike和cancelLike,这样就可以做好防备了

注意点

其实点赞Action的代码还是不够完善

还有问题么.png

因为在实操过程中会出现用户反复狂击点赞按钮的操作,而网络请求又是有延迟的,这样就可能出现两次点赞请求同时发送给了服务器,尽管有些服务器会做限制,但是你本地的代码逻辑将会混乱,造成点赞数显示错误的问题

解决办法:定义点赞按钮的状态

typedef enum : NSUInteger {
    RBCLikeButtonStatusHadThumbs,        //已点赞
    RBCLikeButtonStatusNoneThumbs,       //未点赞
    RBCLikeButtonStatusThumbsing,        //正在点赞
    RBCLikeButtonStatusCancelThumbsing   //正在取消点赞
} RBCLikeButtonStatus;

定义status为点赞按钮的点赞状态

//如果status不是"正在取消点赞""正在点赞""已点赞"的状态时,再执行点赞网络请求
if (   status != RBCLikeButtonStatusCancelThumbsing 
    && status != RBCLikeButtonStatusThumbsing 
    && status != RBCLikeButtonStatusHadThumbs   ) 
{
      //改变本地点赞按钮model的点赞状态 --> 正在点赞
      status = RBCLikeButtonStatusThumbsing;      
      //执行点赞的网络请求                
}
//如果status不是"正在取消点赞""正在点赞""未点赞"的状态时,再执行取消点赞网络请求
if (   status != RBCLikeButtonStatusCancelThumbsing 
    && status != RBCLikeButtonStatusThumbsing 
    && status != RBCLikeButtonStatusNoneThumbs   ) 
{
      //改变本地点赞按钮model的点赞状态 -->正在取消点赞
      status = RBCLikeButtonStatusCancelThumbsing;      
      //执行取消点赞的网络请求                
}

总结

1.有朋友能有更好的思路的话可以与作者交流,有误的地方欢迎指正

2.Demo地址: github.com/TynnPassBy/…

有问题请评论区留言.jpg