c# - 逐个像素地动态绘制和显示,有一些延迟
问题描述
假设我需要一个像素一个像素地绘制一些延迟,以便点一个一个地显示。我写了以下代码:
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 个点,然后将它们全部同时显示在图片框上
我究竟做错了什么 ?我没有找到任何相关的信息。
我将不胜感激任何建议,为什么会发生这种情况以及如何解决它。对不起,我的英语不好。
解决方案
我设法为您制定了一个可行的解决方案:
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
}
}
}
推荐阅读
- android - 注销后使用 Facebook 登录无法进行第二次登录
- centos - centos 不能用 ulimit coredump -c 是无限的
- webpack - Webpack 构建大型生产文件
- python-3.x - 我无法弄清楚为什么它在代码行之后不打印( if 6 <= n <= 20 )
- python - 如何为 gurobi 添加条件
- angularjs - 单击后退按钮时如何保留我的数据?
- node.js - 如何使用 ExpressJS 保持持久的 Cloud Functions 连接
- mysql - 按唯一事件分组并将另一列中存在的所有单个事件相加
- python - 仅获取列的一部分的总计
- php - How to write eloquent left join with subquery?