winform 烟花代码
时间: 2023-08-29 12:12:39 浏览: 48
以下是一个简单的 WinForms 烟花效果代码示例:
```csharp
using System;
using System.Drawing;
using System.Windows.Forms;
namespace Fireworks
{
public partial class Form1 : Form
{
private Random rand = new Random();
public Form1()
{
InitializeComponent();
}
private void Form1_MouseClick(object sender, MouseEventArgs e)
{
int count = rand.Next(10, 30);
while (count-- > 0)
{
Particle p = new Particle(e.Location);
p.Velocity = new Point(rand.Next(-4, 5), rand.Next(-10, -3));
p.Color = Color.FromArgb(255, rand.Next(256), rand.Next(256), rand.Next(256));
particles.Add(p);
}
}
private void timer1_Tick(object sender, EventArgs e)
{
using (Graphics g = this.CreateGraphics())
{
g.Clear(Color.Black);
foreach (Particle p in particles)
{
p.Update();
p.Draw(g);
}
particles.RemoveAll(p => p.IsDead);
}
}
}
public class Particle
{
private const int GRAVITY = 1;
public Point Location { get; set; }
public Point Velocity { get; set; }
public Color Color { get; set; }
public bool IsDead { get; set; }
public Particle(Point location)
{
this.Location = location;
}
public void Update()
{
Velocity.Y += GRAVITY;
Location.X += Velocity.X;
Location.Y += Velocity.Y;
IsDead = Location.Y > 600;
}
public void Draw(Graphics g)
{
g.FillEllipse(new SolidBrush(Color), Location.X, Location.Y, 4, 4);
}
}
}
```
在 Form 的 MouseClick 事件中创建多个颗粒,每个颗粒都有一个随机速度和随机颜色。在计时器的 Tick 事件中更新并绘制所有颗粒,并删除死亡的颗粒。颗粒的更新和绘制在 Particle 类中完成。