iOS 实现点赞的动画


@interface ViewController ()
@property (nonatomic, strong) Person *person;
@property (strong, nonatomic)  UIButton *likeBtn;
@property (nonatomic, strong) CAEmitterLayer *emitterLayer;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self likeAnim];
}

- (void)likeAnim {
    _likeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_likeBtn setImage:[UIImage imageNamed:@"default@2x"] forState:UIControlStateNormal];
    _likeBtn.frame = CGRectMake(100, 200, 37, 35);
    [_likeBtn addTarget:self action:@selector(clickAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_likeBtn];
    [self explosion];
}
// CAEmitterLayer实现爆炸粒子
- (void)explosion{
    _emitterLayer = [CAEmitterLayer layer];
    CAEmitterCell *cell = [[CAEmitterCell alloc] init];
    cell.name = @"explosionCell";
    cell.lifetime = .7;
    cell.birthRate = 4000;
    cell.velocity = 50;
    cell.velocityRange = 15;
    cell.scale = .03;
    cell.scaleRange = .02;
    cell.contents = (id)[UIImage imageNamed:@"sparkle"].CGImage;
    
    _emitterLayer.name = @"explosionLayer";
    _emitterLayer.emitterShape = kCAEmitterLayerCircle;
    _emitterLayer.emitterMode = kCAEmitterLayerOutline;
    _emitterLayer.emitterSize = CGSizeMake(25, 0);
    _emitterLayer.emitterCells = @[cell];
    _emitterLayer.renderMode = kCAEmitterLayerOldestFirst;
    _emitterLayer.masksToBounds = NO;
    _emitterLayer.birthRate = 0;
    _emitterLayer.zPosition = 0;
    _emitterLayer.position = CGPointMake(CGRectGetWidth(_likeBtn.bounds)/2, CGRectGetHeight(_likeBtn.bounds)/2);
    
    [_likeBtn.layer addSublayer:_emitterLayer];
    
}
- (void)clickAction:(UIButton *)sender {
    sender.selected = !sender.selected;
    //关键帧动画
    CAKeyframeAnimation *anim = [CAKeyframeAnimation animationWithKeyPath:@"transform.scale"];
    if (sender.selected) {
        anim.values = @[@1.5, @.8, @1, @1.2, @1];
        anim.duration = .6;
       // 调用
        [self addExplosionAnim];
    }else{
        anim.values = @[@.8, @1.0];
        anim.duration = .4;
    }
    [_likeBtn.layer addAnimation:anim forKey:nil];
}

- (void)addExplosionAnim{
    _emitterLayer.beginTime = CACurrentMediaTime();
    _emitterLayer.birthRate = 1;
    __weak typeof(self) weakSelf = self;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.15 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        weakSelf.emitterLayer.birthRate = 0;
    });
}

你可能感兴趣的:(iOS 实现点赞的动画)