iOS开发 简单海浪动画 WavesView

Simulator Screen Shot 2016年3月25日 上午1.54.38.png

WavesView.gif

WavesView.swift

import UIKit

class WavesView: UIView {
    var waterColor: UIColor!
    var linePointY: CGFloat!
    var a:CGFloat = 1.5
    var b:CGFloat = 0
    var boolValue:Bool = false
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        self.backgroundColor = UIColor.clearColor()
        
        waterColor = UIColor(red: 74/255, green: 144/255, blue: 226/255, alpha: 1)
        linePointY = UIScreen.mainScreen().bounds.height - 250 // 水深
        
        NSTimer.scheduledTimerWithTimeInterval(0.02, target: self, selector: "waveAnimate", userInfo: nil, repeats: true)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func waveAnimate() {
        
        a = boolValue ? (a + 0.01) : (a - 0.01)
        switch a {
        case 0...1:
            boolValue = true
        case 1.5...2:
            boolValue = false
        default:
            break
        }
        b = b + 0.1
        self.setNeedsDisplay()
    }
    
    override func drawRect(rect: CGRect) {
        super.drawRect(rect)
        // 1 获取上下文
        let context = UIGraphicsGetCurrentContext()
        // 2 创建路径
        let path = CGPathCreateMutable()
        CGContextSetLineWidth(context, 1)
        CGContextSetFillColorWithColor(context, waterColor.CGColor)
        
        var y = linePointY
        CGPathMoveToPoint(path, nil, 0, y)
        
        let W = UIScreen.mainScreen().bounds.width //水宽
        for i in 0..<Int(W) {
            y = a * sin( CGFloat(i)/180 * CGFloat(M_PI) + 8 * b/CGFloat(M_PI)) * 5 + linePointY
            CGPathAddLineToPoint(path, nil, CGFloat(i), y)
        }
        
        CGPathAddLineToPoint(path, nil, W, rect.size.height)
        CGPathAddLineToPoint(path, nil, 0, rect.size.height)
        CGPathAddLineToPoint(path, nil, 0, linePointY)
        
        // 3 增加路径到上下文
        CGContextAddPath(context, path)
        CGContextFillPath(context)
        CGContextDrawPath(context, CGPathDrawingMode.FillStroke)
    }
}

ViewController.swift

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 使用
        let waveView = WavesView(frame: self.view.bounds)
        self.view.addSubview(waveView) 
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容