水波动画

作者: c048e8b8e3d7 | 来源:发表于2016-10-18 14:52 被阅读33次
    动画效果

    分析

    每一个水波都是一个CAShapeLayer的实例,然后使用CADisplayLink来刷新界面,每次刷新的时候,CAShapeLayer的形状不一样,在每秒60帧的情况下,看起来就产生了动画效果。

    代码

    下面的示例只创建了一个水波

    @interface JCWaterWave ()
    @property(nonatomic, strong) CADisplayLink *displayLink;
    @property(nonatomic, strong) CAShapeLayer *shapeLayer;
    @property(nonatomic, assign) CGFloat offset;
    
    @end
    
    @implementation JCWaterWave
    
    - (instancetype)initWithFrame:(CGRect)frame
    {
        if (self = [super initWithFrame:frame]) {
            [self setup];
        }
        return self;
    }
    
    - (void)setup
    {
        [self.layer addSublayer:self.shapeLayer];
        [self.displayLink addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];
    }
    
    - (void)startWave
    {
        self.offset += 5;
        [self setFirstLayer];
    }
    
    - (void)setFirstLayer
    {
        CGMutablePathRef path = CGPathCreateMutable();
        
        CGFloat width = self.frame.size.width;
        CGFloat height = self.frame.size.height;
        CGFloat rate = M_PI * 2 / width;//水平上只显示一个波周期
        
        for (CGFloat i = 0.0; i <= width; i++) {
            //5表示振幅
            CGFloat y = sin(rate * (i + self.offset)) * 5 + height / 2.0f;
            if (i > 0.0) {
                CGPathAddLineToPoint(path, nil, i, y);
            } else {
                CGPathMoveToPoint(path, nil, i, y);
            }
        }
        
        CGPathAddLineToPoint(path, nil, width, height);
        CGPathAddLineToPoint(path, nil, 0, height);
        CGPathCloseSubpath(path);
        
        self.shapeLayer.path = path;
        
        CGPathRelease(path);
    }
    
    - (CADisplayLink *)displayLink
    {
        if (!_displayLink) {
            _displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(startWave)];
        }
        return _displayLink;
    }
    
    - (CAShapeLayer *)shapeLayer
    {
        if (!_shapeLayer) {
            _shapeLayer = [CAShapeLayer layer];
            _shapeLayer.fillColor = [UIColor colorWithRed:0 green:0 blue:1 alpha:0.4].CGColor;
        }
        return _shapeLayer;
    }
    
    

    相关文章

      网友评论

        本文标题:水波动画

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