0

该窗体包含一个图片框(picturebox1)和一个定时器控件(timer1)...

基本上在启动时,我创建了一个包含 5 个像素类实例的列表集合。当计时器触发时,我调用调用绘制事件的图片框的刷新。在绘制事件中,我遍历列表集合并调用每个像素的绘制方法。

我遇到的问题是只有一个像素出现......也就是说.. 除非我在添加像素的点设置中断,继续,然后再次中断并重复,直到创建所有 pthe 像素。然后由于某种原因,所有的像素都出现了......

谁能告诉我为什么我只能看到一个像素?

public partial class Form1 : Form
{
    List<Pixel> pixels = new List<Pixel>();

    public Form1()
    {            
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        for (int ii = 0; ii < 5; ii++)
            pixels.Add(new Pixel(pictureBox1));  // <- breakpoint here...?
    }

    private void pictureBox1_Paint(object sender, PaintEventArgs e)
    {
        foreach (Pixel p in pixels)
            p.Draw(e, pictureBox1);
    }

    private void timer1_Tick(object sender, EventArgs e)
    {
        pictureBox1.Refresh();
    }
}

public class Pixel
{
    Random r = new Random(DateTime.Now.Millisecond);

    public Point Position { get; set; }

    public Pixel(PictureBox src) 
    {
        Position = new Point(r.Next(0, src.Width), r.Next(0, src.Height));
    }

    public void Draw(PaintEventArgs e, PictureBox src)
    {
        e.Graphics.DrawRectangle(new Pen(Color.Black), Position.X, Position.Y, 1, 1);
    }
}

我的原始代码做得更多......但我把它全部去掉并得到了相同的结果。

4

2 回答 2

2

由于Random r = new Random(DateTime.Now.Millisecond)每次都使用相同的种子值调用像素,因此像素出现在完全相同的位置。我将 Random 声明移至主类并将其传递给像素类。现在它按我的预期工作。

public partial class Form1 : Form
{
    Random r = new Random(DateTime.Now.Millisecond);
    List<Pixel> pixels = new List<Pixel>();

    public Form1()
    {            
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        for (int ii = 0; ii < 5; ii++)
        {
            pixels.Add(new Pixel(pictureBox1, r));
        }
    }

    private void pictureBox1_Paint(object sender, PaintEventArgs e)
    {
        foreach (Pixel p in pixels)
            p.Draw(e, pictureBox1);
    }

    private void timer1_Tick(object sender, EventArgs e)
    {
        pictureBox1.Refresh();
    }
}

public class Pixel
{
    public Point Position { get; set; }

    public Pixel(PictureBox src, Random r) 
    {
        Position = new Point(r.Next(0, src.Width), r.Next(0, src.Height));
    }

    public void Draw(PaintEventArgs e, PictureBox src)
    {
        e.Graphics.DrawRectangle(new Pen(Color.Black), Position.X, Position.Y, 1, 1);
    }
}
于 2012-10-29T17:23:49.983 回答
-1

这是因为您在像素类的所有 5 个实例上的随机化器都使用完全相同的种子(这一切都发生在相同的毫秒值上)。不要宽恕使用 Thread.Sleep,至少暴露问题的最快“修复”是将您的 form_load 事件更改为如下所示(您也可以重构随机化的方式):

    private void Form1_Load(object sender, EventArgs e)
    {
        for (int ii = 0; ii < 5; ii++)
        {
            Thread.Sleep(1);
            pixels.Add(new Pixel(pictureBox1));
        }
    }
于 2012-10-29T17:31:44.210 回答