思考
类似上图中的水波效果怎样实现?
- 首先需要几个圆圈;
- 需要做放大动画(radius);
- 需要做Alpha的动画;
- 相邻的圆圈 做动画时间需要有间隔;
- 需要无限循环;
根据需求分析
- 需要做两个动画,用CAAnimationGroup;
- 需要做放大动画,用CABasicAnimation, transform.scale.xy;
- 需要做透明度动画,但是不能太突兀, 用CAKeyframeAnimation ,关键帧动画;
- 圆圈不确定,需要根据需求变,这样无法使用固定值,如果循环创建也不是一个好的做法,这样我们就需要用到CAReplicatorLayer,利用它能高效生成许多相似的图层的特性,来解决这个问题
实现
下面贴代码
第一步 新建一个类 继承于CAReplicatorLayer;
@interface DWRipplesLayer : CAReplicatorLayer
第二步 添加属性 (属性的配置我都以懒加载的方式写在了getter方法中)
/**
* 涟漪圈
*/
@property (nonatomic, strong) CALayer *roundLayer;
/**
* 动画组
*/
@property (nonatomic, strong) CAAnimationGroup *ripplesAnimationGroup;
/**
* 涟漪圈半径的初始值
*/
@property (nonatomic, assign) CGFloat fromValueForRadius;
/**
* 涟漪圈Alpha初始值
*/
@property (nonatomic, assign) CGFloat fromValueForAlpha;
第三步 将 roundLayer 添加到self上 并做一些初始值设置
- (instancetype)init{
if (self = [super init]) {
[self addSublayer:self.roundLayer];
[self setUp];
}
return self;
}
#pragma mark - Private Methods
- (void)setUp{
self.roundLayer.backgroundColor = [[UIColor greenColor] CGColor];
self.radius = 60;
self.animationDuration = 3;
self.fromValueForAlpha = 0.f;
self.fromValueForRadius = 0.f;
// 必须 CAReplicatorLayer的重要特性
self.repeatCount = INFINITY;
self.instanceCount = 3;
self.instanceDelay = 1;
}
第四步 配置动画
#pragma mark - Private Methods
- (void)setUpAnimation{
self.ripplesAnimationGroup.duration = self.animationDuration;
self.ripplesAnimationGroup.repeatCount = self.repeatCount;
self.ripplesAnimationGroup.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionDefault];;
// 圆圈放大
CABasicAnimation *scaleAnimation = [CABasicAnimation animationWithKeyPath:@"transform.scale.xy"];
scaleAnimation.fromValue = @(self.fromValueForRadius);
scaleAnimation.toValue = @1.0;
scaleAnimation.duration = self.animationDuration;
// 改变 alpha (关键帧动画)
CAKeyframeAnimation *opacityAnimation = [CAKeyframeAnimation animationWithKeyPath:@"opacity"];
opacityAnimation.values = @[@(self.fromValueForAlpha), @0.5, @0];
opacityAnimation.keyTimes = @[@0, @(0.4), @1];
opacityAnimation.duration = self.animationDuration;
self.ripplesAnimationGroup.animations = @[scaleAnimation, opacityAnimation];
}
最后 给外界一个开始动画的方法
#pragma mark - Public Methods
- (void)startAnimation{
[self setUpAnimation];
[self.roundLayer addAnimation:self.ripplesAnimationGroup forKey:@"ripples"];
}
使用 只需要将layer 插入到你想要做效果的layer的下方
self.frontView = [[UIView alloc] initWithFrame:CGRectMake(100, 100, 30, 30)];
self.frontView.backgroundColor = [UIColor grayColor];
[self.view addSubview:self.frontView];
self.ripplesLayer = [[DWRipplesLayer alloc] init];
[self.view.layer insertSublayer:self.ripplesLayer below:self.frontView.layer];
self.ripplesLayer.position = self.frontView.center;
[self.ripplesLayer startAnimation];