煙花效果
//
// Fireworks.swift
import SwiftUI
// MARK: - 煙花
struct FireworksView: UIViewRepresentable {
func updateUIView(_ uiView: UIView, context: Context) {
}
func makeUIView(context: Context) -> UIView {
//大小充滿(mǎn)整個(gè)屏幕
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)
}
}
}
蘋(píng)果應(yīng)用商店|搜|王勛才|有我全部作品