最近有个朋友的项目里面做了波浪动画效果,刚好我的项目里也有这个需求,就把他的代码拿来改了,主要是实现了颜色渐变的效果。
Github
CocoaChina
废话不多话,说一下实现过程:
1、波纹动画主要依赖于CAShapeLayer的绘制,使用帧动画实现;需要使用多个CAShapeLayer通过y值变换组成(这里我只是用了2个CAShapeLayer)。
2、渐变色由CAGradientLayer完成。
- (void)changeFirstWaveLayerPath {
CGMutablePathRef path = CGPathCreateMutable();
CGFloat y = _wavePointY;
CGPathMoveToPoint(path, nil, 0, y);
for (float x = 0.0f; x <= _waveWidth; x ++) {
y = _waveAmplitude * 1.6 * sin((250 / _waveWidth) * (x * M_PI / 180) - _waveOffsetX * M_PI / 270) + _wavePointY;
CGPathAddLineToPoint(path, nil, x, y);
}
CGPathAddLineToPoint(path, nil, _waveWidth, 0);
CGPathAddLineToPoint(path, nil, 0, 0);
CGPathCloseSubpath(path);
_shapeLayer1.path = path;
CGPathRelease(path);
}
- (void)changeSecondWaveLayerPath {
CGMutablePathRef path = CGPathCreateMutable();
CGFloat y = _wavePointY;
CGPathMoveToPoint(path, nil, 0, y);
for (float x = 0.0f; x <= _waveWidth; x ++) {
y = _waveAmplitude * 1.6 * sin((250 / _waveWidth) * (x * M_PI / 180) - _waveOffsetX * M_PI / 180) + _wavePointY;
CGPathAddLineToPoint(path, nil, x, y);
}
CGPathAddLineToPoint(path, nil, _waveWidth, 0);
CGPathAddLineToPoint(path, nil, 0, 0);
CGPathCloseSubpath(path);
_shapeLayer2.path = path;
CGPathRelease(path);
}
调用:
_waveOffsetX += _waveSpeed;
[self changeFirstWaveLayerPath];
[self changeSecondWaveLayerPath];
[self.layer addSublayer:self.gradientLayer1];
self.gradientLayer1.mask = _shapeLayer1;
[self.layer addSublayer:self.gradientLayer2];
self.gradientLayer2.mask = _shapeLayer2;
如果需要纯色背景的话 可以删除CAGradientLayer,给View和CAShapeLayer设置背景色;或者2个Color颜色值给相同的。
网友评论