
思路
簡(jiǎn)單的波浪,讓我想起了三角函數(shù)。

正余弦函數(shù)
所以我們只要先畫(huà)出靜態(tài)的三角函數(shù)圖形,然后讓它有平移的視覺(jué)效果,也就產(chǎn)生了動(dòng)畫(huà)。
實(shí)現(xiàn)
- 橫坐標(biāo)的范圍為0到視圖寬度。
- 為了增強(qiáng)視覺(jué)效果,我們需要將顯示的三角函數(shù)圖的范圍限定在一個(gè)周期內(nèi),所以sin(x),此處x的范圍必須是0到2π。所以y = sin(x/(width0.5)M_PI)。
- 根據(jù)上述得到了不動(dòng)的圖。為了讓函數(shù)水平移動(dòng)就要隨著時(shí)間增加給sin(x)中的x添加變量distance。
- 將上述邏輯結(jié)合在“drawRect:”方法里實(shí)現(xiàn)繪制。
代碼
#import <UIKit/UIKit.h>
@interface TCWave : UIView
/** 水的顏色 */
@property (nonatomic, strong) UIColor *waterColor;
/** 波浪變化的頻率 */
@property (nonatomic) CGFloat refreshFrequency;
/** 振幅 默認(rèn) 10*/
@property (nonatomic) CGFloat waveHeight;
@end
#import "TCWave.h"
@interface TCWave ()
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic) CGFloat distance;
@end
@implementation TCWave
- (instancetype)init {
if (self = [super init]) {
_waveHeight = 10;
_waterColor = [UIColor colorWithRed:86/255.0f green:202/255.0f blue:139/255.0f alpha:1];
}
return self;
}
- (instancetype)initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
_waveHeight = 10;
_waterColor = [UIColor colorWithRed:86/255.0f green:202/255.0f blue:139/255.0f alpha:1];
}
return self;
}
- (void)awakeFromNib {
[super awakeFromNib];
_waveHeight = 10;
_waterColor = [UIColor colorWithRed:86/255.0f green:202/255.0f blue:139/255.0f alpha:1];
}
- (void)setRefreshFrequency:(CGFloat)refreshFrequency {
_refreshFrequency = refreshFrequency;
[self.timer invalidate];
self.timer = [NSTimer scheduledTimerWithTimeInterval:refreshFrequency target:self selector:@selector(animateWave) userInfo:nil repeats:YES];
}
-(void)animateWave {
self.distance += 0.1;
[self setNeedsDisplay];
}
- (void)drawRect:(CGRect)rect {
CGContextRef context = UIGraphicsGetCurrentContext();
CGMutablePathRef path = CGPathCreateMutable();
//畫(huà)水
CGContextSetLineWidth(context, 1);
CGContextSetFillColorWithColor(context, self.waterColor.CGColor);
CGContextSetStrokeColorWithColor(context, self.waterColor.CGColor);
float y = _waveHeight/2;
CGPathMoveToPoint(path, NULL, 0, y);
for(float x=0;x<=rect.size.width;x++){
y = _waveHeight/2 * sin(x/(rect.size.width*0.5)*M_PI + self.distance) + _waveHeight/2;
CGPathAddLineToPoint(path, nil, x, y);
}
CGPathAddLineToPoint(path, nil, rect.size.width, rect.size.height);
CGPathAddLineToPoint(path, nil, 0, rect.size.height);
CGPathAddLineToPoint(path, nil, 0, _waveHeight/2);
CGContextAddPath(context, path);
CGContextFillPath(context);
CGContextDrawPath(context, kCGPathStroke);
CGPathRelease(path);
}
@end
Demo
具體演示工程請(qǐng)點(diǎn)擊鏈接下載,如果覺(jué)得有用,請(qǐng)幫我star一下,非常感謝!
TCWave