动态地逐点绘制和显示像素

时间:2018-12-15 13:35:30

标签: c# multithreading image bitmap

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

            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上。

我做错了什么?我什么都没找到。

对于任何建议,为什么会发生以及如何解决,我将不胜感激。 对不起,我的英语不好。

1 个答案:

答案 0 :(得分:0)

我设法为您提供了可行的解决方案:

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
        }
    }
}