标签:
做购物应用的时候,有点时候需要这样一个动画
我照着动画效果来实现一下看看
storyboard中拖入一个UIButton和一个UIImageView
代码如下:
// // ViewController.m // test // // Created by hqw on 16/4/20. // Copyright © 2016年 hgs. All rights reserved. // #import "ViewController.h" @interface ViewController () @property (weak, nonatomic) IBOutlet UIImageView *imageView; @property (weak, nonatomic) IBOutlet UIButton *btn; @property (nonatomic, strong) NSMutableArray *layerArray; @end @implementation ViewController //记录用户点击次数 static NSInteger i = 0; static NSInteger j = 0; - (NSMutableArray *)layerArray { if (_layerArray == nil) { _layerArray = [[NSMutableArray alloc] init]; } return _layerArray; } - (IBAction)btnClick:(UIButton *)sender { CALayer *layer = [CALayer layer]; //将产生的layer添加进数组 [self.layerArray addObject:layer]; layer.frame = sender.frame; UIImage *image = [UIImage imageNamed:@"btn_add_cart"]; layer.contents = (id)image.CGImage; [self.view.layer addSublayer:layer]; //path UIBezierPath *path = [UIBezierPath bezierPath]; [path moveToPoint:sender.center]; CGFloat x = (self.imageView.center.x - sender.center.x) / 2.0 - 50; CGFloat y = (sender.center.y - self.imageView.center.y) / 2; [path addQuadCurveToPoint:self.imageView.center controlPoint:CGPointMake(sender.center.x + x, y)]; [self startAnimation:path layer:layer]; } - (void)startAnimation:(UIBezierPath *)path layer:(CALayer *)layer { CAAnimationGroup *group = [CAAnimationGroup animation]; CAKeyframeAnimation *keyAnim = [CAKeyframeAnimation animationWithKeyPath:@"position"]; keyAnim.path = path.CGPath; CABasicAnimation *baseAnim = [CABasicAnimation animationWithKeyPath:@"opacity"]; baseAnim.toValue = @0.01; group.animations = @[keyAnim, baseAnim]; group.duration = 1; group.delegate = self; [layer addAnimation:group forKey:nil]; } - (void)animationDidStart:(CAAnimation *)anim { i++; } - (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag { //动画结束,遍历移除layer //可能有人会直接用属性引用layer移除,但是如果用户快速点多次,那么layer就不会移除了,所以,用数组来记录 j++; if (i == j) {//i==j的时候,说明所有的动画都结束了,这个时候就移除所有layer for (CALayer *layer in self.layerArray) { [layer removeFromSuperlayer]; } //记得清空数组 [self.layerArray removeAllObjects]; } }
这么做就完美了,那个判断i和j相等移除layer的做法让我想了很久(呵呵,如果你想到了更好的办法也可以告诉我).
其实我在iPad上做的时候,会闪,我也说下怎么解决吧.
会闪其实是由于两个图片不一致导致的,一个是按钮,一个是图片,如果尺寸都一样,但是设置图片之后,图片的大小是不一样的(好绕),总之就是不一样大
这个时候我会用UIImgeView来代替UIButton,无非多增加一行手势代码而已,然后其他的不变.若是不要按钮的高亮,自定义按钮就够了.
最后上一波图:
标签:
原文地址:http://www.cnblogs.com/chiefhe/p/5412607.html