美文网首页程序员
做一个简单的波浪动画

做一个简单的波浪动画

作者: 范德萨范德萨范德萨 | 来源:发表于2017-08-31 15:41 被阅读47次

思路

简单的波浪,让我想起了三角函数。


正余弦函数正余弦函数

所以我们只要先画出静态的三角函数图形,然后让它有平移的视觉效果,也就产生了动画。

实现

  • 横坐标的范围为0到视图宽度。
  • 为了增强视觉效果,我们需要将显示的三角函数图的范围限定在一个周期内,所以sin(x),此处x的范围必须是0到2π。所以y = sin(x/(width0.5)M_PI)。
  • 根据上述得到了不动的图。为了让函数水平移动就要随着时间增加给sin(x)中的x添加变量distance。
  • 将上述逻辑结合在“drawRect:”方法里实现绘制。

代码

#import <UIKit/UIKit.h>

@interface TCWave : UIView
/** 水的颜色 */
@property (nonatomic, strong) UIColor *waterColor;
/** 波浪变化的频率 */
@property (nonatomic) CGFloat refreshFrequency;
/** 振幅 默认 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();
    
    //画水
    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

具体演示工程请点击链接下载,如果觉得有用,请帮我star一下,非常感谢!
TCWave

相关文章

网友评论

    本文标题:做一个简单的波浪动画

    本文链接:https://www.haomeiwen.com/subject/hepqjxtx.html