CAEmitterCell の色を変更できなかった理由 UIImage で systemName パラメータを使用しており、SFSymbols で定義されたアイコンを使用しています。CAEmitterCell の色を変更できませんでした。cgColor プロパティを追加しましたが、それでもコードが機能しませんでした。
使用する
ParticleEffectView(particleImages: ["a.circle","b.circle","c.circle"])
パーティクルエフェクト ビュー
struct ParticleEffectView: UIViewRepresentable {
var particleImages: [String]
func makeUIView(context: Context) -> UIView {
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 = .rectangle
particlesLayer.emitterPosition = CGPoint(x: UIScreen.main.bounds.width / 2, y: UIScreen.main.bounds.height / 2)
particlesLayer.emitterSize = CGSize(width: UIScreen.main.bounds.width * 2, height: UIScreen.main.bounds.height * 2)
particlesLayer.emitterMode = .outline
particlesLayer.renderMode = .backToFront
particlesLayer.emitterCells = prepareParticeCell(particles: particleImages, color: UIColor.orange)
return host
}
func prepareParticeCell(particles: [String], color: UIColor) -> [CAEmitterCell] {
var arrayParticleCell: [CAEmitterCell] = [CAEmitterCell]()
for particleItem in particles {
let particleCell: CAEmitterCell = CAEmitterCell()
particleCell.contents = UIImage(systemName: particleItem)?.cgImage
particleCell.name = "XO"
particleCell.birthRate = 10
particleCell.lifetime = 20.0
particleCell.lifetimeRange = 0
particleCell.velocity = 100
particleCell.velocityRange = 100 / 4
particleCell.emissionLongitude = .pi
particleCell.emissionRange = .pi / 8
particleCell.scale = 0.5
particleCell.scaleRange = 0.5 / 3
particleCell.color = color.cgColor //here
arrayParticleCell.append(particleCell)
}
return arrayParticleCell
}
func updateUIView(_ uiView: UIView, context: Context) {
uiView.insetsLayoutMarginsFromSafeArea = false
}
}