烟花效果
//
// Fireworks.swift
import SwiftUI
// MARK: - 烟花
struct FireworksView: UIViewRepresentable {
func updateUIView(_ uiView: UIView, context: Context) {
}
func makeUIView(context: Context) -> UIView {
//大小充满整个屏幕
let view = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height))
//背景透明
view.backgroundColor = .clear
//粒子层
let emitterLayer = CAEmitterLayer()
emitterLayer.emitterSize = view.bounds.size
emitterLayer.emitterShape = .rectangle
emitterLayer.position = CGPoint(x: view.bounds.midX, y: view.bounds.midY)
emitterLayer.renderMode = .additive
// 烟花种子
let seedCell = CAEmitterCell()
seedCell.color = UIColor(red: 0.5, green: 0.5, blue: 0.5, alpha: 0.2).cgColor
seedCell.redRange = 0.8
seedCell.greenRange = 0.8
seedCell.blueRange = 0.8
seedCell.lifetime = 1
seedCell.birthRate = 4
// 烟花
let fireworkCell = CAEmitterCell()
fireworkCell.contents = UIImage(named: "star")?.cgImage
fireworkCell.alphaRange = 0.1
fireworkCell.lifetime = 100
fireworkCell.lifetimeRange = 10
fireworkCell.birthRate = 10_000
fireworkCell.velocity = 200
fireworkCell.scale = 0.2
fireworkCell.spin = 3
fireworkCell.alphaSpeed = -0.2
fireworkCell.scaleSpeed = -0.1
fireworkCell.duration = 0.1
fireworkCell.emissionRange = CGFloat.pi * 2
fireworkCell.yAcceleration = 80
seedCell.emitterCells = [fireworkCell]
emitterLayer.emitterCells = [seedCell]
view.layer.insertSublayer(emitterLayer, at: 0)
return view
}
}
使用方法
//
import SwiftUI
struct ContentView: View {
var body: some View {
//使用
ZStack {
//背景颜色置黑,模拟夜空
Color.black.ignoresSafeArea()
FireworksView()
.ignoresSafeArea()
Text("烟花").font(.largeTitle).foregroundColor(.white)
}
}
}
苹果应用商店|搜|王勋才|有我全部作品