Swift---面向协议开发
- 先创建一个snow.swift文件 这是一个协议
import UIKit
import QuartzCore
protocol snow { // 空的协议
}
extension snow where Self : UIView { 对协议进行拓展 where Self 限定此协议的使用范围只能值UIView
func createSnow() {
// 1.创建粒子发射器
let emitter = self.layer as! CAEmitterLayer
// 1.1 设置粒子发射器的位置
emitter.emitterPosition = CGPoint(x: 0, y: 0)
// 1.2 设置粒子发射器的范围
emitter.emitterSize = bounds.size
// 1.3 设置粒子的形状
emitter.emitterShape = kCAEmitterLayerRectangle
// 2. 创建粒子
let emitterCell = CAEmitterCell()
// 2.1载入粒子
emitterCell.contents = UIImage(named: "snowflake1")!.cgImage
// 2.2设置粒子的出生速率
emitterCell.birthRate = 400
// 2.3设置每个粒子的生命周期
emitterCell.lifetime = 3.5
// 2.4粒子的颜色
emitterCell.color = UIColor.white.cgColor
// 2.5RGBA设置
emitterCell.redRange = 0.0 // RGBA设置
emitterCell.blueRange = 0.1
emitterCell.greenRange = 0.0
emitterCell.alphaRange = 0.5
emitterCell.velocity = 9.8 // 重力加速度也就是物理里面G
emitterCell.velocityRange = 550 // 加速范围
emitterCell.emissionRange = CGFloat(M_PI_2) // 下落是旋转的角度
emitterCell.emissionLongitude = CGFloat(-M_PI) //
emitterCell.yAcceleration = 70
emitterCell.xAcceleration = 0
emitterCell.scale = 0.33 // 发射比例
emitterCell.scaleRange = 1.25
emitterCell.scaleSpeed = -0.25
emitterCell.alphaRange = 0.5 // 透明度调整
emitterCell.alphaSpeed = -0.15
emitter.emitterCells = [emitterCell] // 载入
}
}
- 创建一个继承UIView的SnowView
class SnowView: UIView , snow{
override init(frame: CGRect) {
super.init(frame: frame)
createSnow()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// 这个方法一定要重写 不然会在这个位置___let emitter = self.layer as! CAEmitterLayer____报类型不匹配的错误
override class var layerClass: AnyClass {
return CAEmitterLayer.self
}
}
3.创建snowView.添加到控制器的View上
class ViewController: UIViewController {
var snowview: SnowView?
override func viewDidLoad() {
super.viewDidLoad()
snowview = SnowView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height))
let snowClipView = UIView(frame: view.bounds)
snowClipView.clipsToBounds = true
snowClipView.addSubview(snowview!)
view.addSubview(snowClipView)
}
}