运行效果
波浪效果图
实现思路
定义一个View,并增加圆形或者自定义背景视图
画出静态正弦函数
遮罩,mask层
定时器,不断的改变路径上的各个点,让波浪动起来
难点
三角函数:假设 y = Asin(ωx+φ)+ C
A 表示振幅,也就是使用这个变量来调整波浪的最大的高度
ω 与周期相关,周期 T = 2 x pi / ω 即这个变量用来调整同宽度内显示的波浪的数量
φ 表示波浪横向的偏移,也就是使用这个变量来调整波浪的流动
C 表示波浪纵向偏移的位置。
如果你的三角函数还给了敬爱的老师,我在网上大概找了一下比较详细的教程可以参考下:
正弦函数伸缩变换
1.画出静态三角函数
- (void)drawWaterWave{ CGMutablePathRef path = CGPathCreateMutable(); CGPathMoveToPoint(path, NULL, 0, VIEW_HEIGHT/2.0); for (int i = 0; i <= VIEW_WIDTH ; i++) { CGFloat y = kWaveYMax * sin(kWaveDuration*i+self.waveOffset) + kWaveYOffset; CGPathAddLineToPoint(path, NULL, i, y); } CGPathAddLineToPoint(path, NULL,VIEW_WIDTH, VIEW_HEIGHT); CGPathAddLineToPoint(path, NULL, 0, VIEW_HEIGHT); CGPathCloseSubpath(path); self.waveLayer.path = path; CGPathRelease(path); }
2.定时器改变正弦的参数计算出新的位移,然后绘制
- (void)changeWave{ self.waveOffset += kWaveMoveSpeed; [self setNeedsDisplay]; } - (CADisplayLink *)displayLink{ if (_displayLink == nil) { CADisplayLink * displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(changeWave)]; [displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes]; _displayLink = displayLink; } return _displayLink; }
3.添加背景,并且为上述绘制的波浪添加遮罩
- (CAShapeLayer *)circleShapeLayer{ if (_circleShapeLayer == nil) { CAShapeLayer * cirShapeLayer = [CAShapeLayer layer]; [self.layer addSublayer:cirShapeLayer]; UIBezierPath *bPath = [UIBezierPath bezierPathWithArcCenter:CGPointMake(VIEW_WIDTH/2.0, VIEW_HEIGHT/2.0) radius:VIEW_WIDTH/2.0 - kWaveMargin startAngle:0 endAngle:2*M_PI clockwise:YES]; cirShapeLayer.path = bPath.CGPath; _circleShapeLayer = cirShapeLayer; } return _circleShapeLayer; } - (CAShapeLayer *)waveLayer{ if (_waveLayer == nil) { CAShapeLayer * shapeLayer = [CAShapeLayer layer]; shapeLayer.fillColor = [UIColor grayColor].CGColor; shapeLayer.lineWidth = 2.0f; shapeLayer.strokeColor = [UIColor redColor].CGColor; [self.layer addSublayer:shapeLayer]; shapeLayer.mask = self.circleShapeLayer; _waveLayer = shapeLayer; } return _waveLayer; } -(CAShapeLayer *)backShapeLayer{ if (_backShapeLayer == nil) { UIBezierPath *bPath = [UIBezierPath bezierPathWithArcCenter:CGPointMake(VIEW_WIDTH/2.0, VIEW_HEIGHT/2.0) radius:VIEW_WIDTH/2.0 - kWaveMargin startAngle:0 endAngle:2*M_PI clockwise:YES]; CAShapeLayer * backShapeLayer = [CAShapeLayer layer]; backShapeLayer.path = bPath.CGPath; backShapeLayer.lineWidth = 3.0f; backShapeLayer.fillColor = [UIColor clearColor].CGColor; backShapeLayer.strokeColor = [UIColor blueColor].CGColor; [self.layer addSublayer:backShapeLayer]; _backShapeLayer = backShapeLayer; } return _backShapeLayer; }
以上完成后,水波动画就可以正常运行了,根本停不下来!
本文只贴了核心的部分,如需完整,点我下载。