項目中有時會用到波浪效果嗡午,效果如下:
具體代碼如下:1.首先要創(chuàng)建個時間控制器,波浪一直處于動態(tài),所以必須要有個定時器方法如下:
接著在定時器方法里寫移動效果释簿,這有這樣才會讓人覺得波浪再動!代碼如下:
下面就是開始繪制兩條波浪線偏螺。要在:- (void)drawRect:(CGRect)rect方法里創(chuàng)建,iOS系統(tǒng)里有個CGContextRef類匆光,是專門用來繪圖套像,里面有很多方法。只介紹水波紋的终息。具體方法:
- (void)drawRect:(CGRect)rect {
CGContextRef context = UIGraphicsGetCurrentContext(); // 路徑
// 創(chuàng)建路徑
CGMutablePathRef path = CGPathCreateMutable();
// 畫水波紋
CGContextSetLineWidth(context, 1); // 水波紋寬
UIColor *color = [UIColor colorWithColorString:@"#000000" alpha:0.15];
//? ? UIColor *color = [UIColor clearColor];
CGContextSetFillColorWithColor(context, [color CGColor]);// 背景色
// 設(shè)置波峰高度
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++) {
// 構(gòu)造正弦函數(shù)
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);
}
// 對正弦函數(shù)進行波長波谷約束
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