效果展示
具体流程
一、封装YDWLikeButton
- 新建一个YDWLikeButton继承于UIButton,然后声明一个属性:
@property (nonatomic, strong) CAEmitterLayer *explosionLayer;
- (void)awakeFromNib{
[super awakeFromNib];
[self setupExplosion];
}
- (instancetype)initWithFrame:(CGRect)frame{
self = [super initWithFrame:frame];
if (self) {
[self setupExplosion];
}
return self;
}
CAEmitterCell * explosionCell = [CAEmitterCell emitterCell];
explosionCell.name = @"explosionCell";
explosionCell.alphaSpeed = -1.f;
explosionCell.alphaRange = 0.10;
explosionCell.lifetime = 1;
explosionCell.lifetimeRange = 0.1;
explosionCell.velocity = 40.f;
explosionCell.velocityRange = 10.f;
explosionCell.scale = 0.08;
explosionCell.scaleRange = 0.02;
explosionCell.contents = (id)[[UIImage imageNamed:@"spark_red"] CGImage];
CAEmitterLayer * explosionLayer = [CAEmitterLayer layer];
[self.layer addSublayer:explosionLayer];
self.explosionLayer = explosionLayer;
self.explosionLayer.emitterSize = CGSizeMake(self.bounds.size.width + 40, self.bounds.size.height + 40);
explosionLayer.emitterShape = kCAEmitterLayerCircle;
explosionLayer.emitterMode = kCAEmitterLayerOutline;
explosionLayer.renderMode = kCAEmitterLayerOldestFirst;
explosionLayer.emitterCells = @[explosionCell];
- (void)setSelected:(BOOL)selected{
[super setSelected:selected];
CAKeyframeAnimation * animation = [CAKeyframeAnimation animation];
animation.keyPath = @"transform.scale";
if (selected) {
animation.values = @[@1.5,@2.0, @0.8, @1.0];
animation.duration = 0.5;
animation.calculationMode = kCAAnimationCubic;
[self.layer addAnimation:animation forKey:nil];
[self performSelector:@selector(startAnimation) withObject:nil afterDelay:0.25];
} else {
[self stopAnimation];
}
}
- (void)startAnimation{
[self.explosionLayer setValue:@1000 forKeyPath:@"emitterCells.explosionCell.birthRate"];
self.explosionLayer.beginTime = CACurrentMediaTime();
[self performSelector:@selector(stopAnimation) withObject:nil afterDelay:0.15];
}
- (void)stopAnimation{
[self.explosionLayer setValue:@0 forKeyPath:@"emitterCells.explosionCell.birthRate"];
[self.explosionLayer removeAllAnimations];
}
二、使用YDWLikeButton
YDWLikeButton * btn = [YDWLikeButton buttonWithType:UIButtonTypeCustom];
btn.frame = CGRectMake(200, 150, 30, 130);
[self.view addSubview:btn];
[btn setImage:[UIImage imageNamed:@"dislike"] forState:UIControlStateNormal];
[btn setImage:[UIImage imageNamed:@"like_orange"] forState:UIControlStateSelected];
[btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
- (void)btnClick:(UIButton *)button{
if (!button.selected) {
button.selected = !button.selected;
NSLog(@"点赞");
} else {
button.selected = !button.selected;
NSLog(@"取消赞");
}
}
完整示例传送门
仿QQ点赞按钮的粒子效果