Simulator Screen Shot 2016年3月25日 上午1.54.38.png
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)
}
}