以一定的延迟逐像素动态绘制和显示



假设我需要以一定的延迟逐像素绘制,以便逐点显示。我写了以下代码:

for (int i = 0; i < 300; ++i)
{
Random random = new Random();
Point point = new Point(random.Next(0, bmp.Width), random.Next(0, bmp.Height));
bmp.SetPixel(point.X, point.Y, Color.Black);
pictureBox1.Image = bmp;
Thread.Sleep(10);
}

但它不起作用!程序冻结,直到位图上设置了300个点,然后在pictureBox 上同时显示所有点

我做错了什么?我什么也没发现。

我将感谢任何建议,为什么会发生这种情况以及如何解决它。抱歉我英语不好。

我设法为您制定了一个可行的解决方案:

public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private Bitmap bmp = new Bitmap(100,100);
private void Form1_Load(object sender, EventArgs e)
{
pictureBox1.Image = bmp; //only assign it once!
}
private async void button1_Click(object sender, EventArgs e)
{ // method that starts the picturebox filling. You can declare it anywhere else.
for (int i = 0; i < 300; ++i)
{
Random random = new Random();
Point point = new Point(random.Next(0, bmp.Width), random.Next(0, bmp.Height));
bmp.SetPixel(point.X, point.Y, Color.Black); //we are updating the reference of 'bmp', which the pictureBox already contains
pictureBox1.Refresh(); //force the picturebox to redraw its bitmap
await Task.Delay(100); // async delay, to prevent the UI from locking
}
}
}

相关内容

  • 没有找到相关文章

最新更新