当我添加多个对象时,我必须一一写如下。当我想添加 2 个或更多对象时,我总是必须复制和粘贴。我不希望这样,我尝试用 forLoop 来做,但我只看到最后添加的任何对象。
循环
我写了一个函数。ForLoop 的工作量与数组中的图像数量一样多。
func prepareParticeCell(particles: [String]) -> CAEmitterCell {
let particleCell = CAEmitterCell()
for particleItem in particles {
let particle = UIImage(named: particleItem)?.cgImage
particleCell.contents = particle
particleCell.name = "Square"
particleCell.birthRate = 5
particleCell.lifetime = 74.5
particleCell.velocityRange = 0.0
particleCell.velocity = 79.0
particleCell.xAcceleration = 0.0
particleCell.yAcceleration = 0.0
particleCell.emissionLatitude = 1*6.0 * (.pi / 180)
particleCell.emissionLongitude = -105.0 * (.pi / 180)
particleCell.emissionRange = 360.0 * (.pi / 180.0)
particleCell.spin = -65.6 * (.pi / 180.0)
particleCell.spinRange = 314.2 * (.pi / 180.0)
particleCell.scale = 0.043
particleCell.scaleRange = 0.7
particleCell.scaleSpeed = 0.02
particleCell.alphaRange = 0.0
particleCell.alphaSpeed = 0.47
particleCell.color = UIColor(red: 255.0/255.0, green: 255.0/255.0, blue: 255.0/255.0, alpha: 1.0).cgColor
}
return particleCell
}
使用功能
let host = UIView(frame: CGRect(x: 0.0, y: 0.0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height))
let particlesLayer = CAEmitterLayer()
particlesLayer.frame = CGRect(x: 0.0, y: 0.0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)
host.layer.insertSublayer(particlesLayer, at: 0)
host.layer.masksToBounds = true
host.insetsLayoutMarginsFromSafeArea = false
particlesLayer.backgroundColor = .none
particlesLayer.emitterShape = .circle
particlesLayer.emitterPosition = CGPoint(x: 509.4, y: 707.7)
particlesLayer.emitterSize = CGSize(width: 1648.0, height: 1112.0)
particlesLayer.emitterMode = .outline
particlesLayer.renderMode = .backToFront
particlesLayer.emitterCells = [prepareParticeCell(particles: particleImages)] // here
return host