首页 > 解决方案 > 逐个像素地动态绘制和显示,有一些延迟

问题描述

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

            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 个点,然后将它们全部同时显示在图片框上

我究竟做错了什么 ?我没有找到任何相关的信息。

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

标签: c#multithreadingimagebitmap

解决方案


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

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

推荐阅读