iOS开发 简单海浪动画 WavesView

iOS开发 简单海浪动画 WavesView_第1张图片
Simulator Screen Shot 2016年3月25日 上午1.54.38.png

iOS开发 简单海浪动画 WavesView_第2张图片
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..

ViewController.swift

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 使用
        let waveView = WavesView(frame: self.view.bounds)
        self.view.addSubview(waveView) 
    }
}

你可能感兴趣的:(iOS开发 简单海浪动画 WavesView)