项目中有时会用到波浪效果,效果如下:
具体代码如下:1.首先要创建个时间控制器,波浪一直处于动态,所以必须要有个定时器方法如下:
接着在定时器方法里写移动效果,这有这样才会让人觉得波浪再动!代码如下:
下面就是开始绘制两条波浪线。要在:- (void)drawRect:(CGRect)rect方法里创建,iOS系统里有个CGContextRef类,是专门用来绘图,里面有很多方法。只介绍水波纹的。具体方法:
- (void)drawRect:(CGRect)rect {
CGContextRef context = UIGraphicsGetCurrentContext(); // 路径
// 创建路径
CGMutablePathRef path = CGPathCreateMutable();
// 画水波纹
CGContextSetLineWidth(context, 1); // 水波纹宽
UIColor *color = [UIColor colorWithColorString:@"#000000" alpha:0.15];
// UIColor *color = [UIColor clearColor];
CGContextSetFillColorWithColor(context, [color CGColor]);// 背景色
// 设置波峰高度
float y = (1 - self.present) * rect.size.height;
float y1 = (1 - self.present) * rect.size.height;
CGPathMoveToPoint(path, NULL, 0, y);
for (float x = 0; x <= rect.size.width * 3.0; x++) {
// 构造正弦函数
y = sin(x / (rect.size.width / 5) * M_PI + _fa / (rect.size.width / 5) * M_PI) * _bigNumber + (1 - self.present) * rect.size.height;
CGPathAddLineToPoint(path, nil, x, y);
}
// 对正弦函数进行波长波谷约束
CGPathAddLineToPoint(path, nil, rect.size.width, rect.size.height);
CGPathAddLineToPoint(path, nil, 0, rect.size.height);
CGContextAddPath(context, path);
CGContextFillPath(context);
CGContextDrawPath(context, kCGPathStroke);
CGPathRelease(path);
CGMutablePathRef path1 = CGPathCreateMutable();
// 画第二条线
CGContextSetLineWidth(context, 1);
// UIColor *color1 = [UIColor clearColor];
UIColor *color1 = [UIColor colorWithColorString:@"#000000" alpha:0.20];
CGContextSetFillColorWithColor(context, [color1 CGColor]);
CGPathMoveToPoint(path1, NULL, 0, y1);
for (float x = 0; x <= rect.size.width; x++) {
y1 = sin(x / (rect.size.width / 5) * M_PI + _fa / (rect.size.width / 5) * M_PI + M_PI) *_bigNumber + (1 - self.present) * rect.size.height;
CGPathAddLineToPoint(path1, nil, x, y1);
}
CGPathAddLineToPoint(path1, nil, rect.size.height, rect.size.width);
CGPathAddLineToPoint(path1, nil, 0, rect.size.height);
CGContextAddPath(context, path1);
CGContextFillPath(context);
CGContextDrawPath(context, kCGPathStroke);
CGPathRelease(path1);
}
最后一步就是给一个波浪幅度值,并起吊定时器。
具体代码地址:https://github.com/likelk/WaterRippleAnimation.git