为什么PictureBox在表单中定位后才出现?

时间:2015-10-12 01:25:31

标签: c# windows-forms-designer

我有这类鱼,我只是想用8种类型的鱼将其形状初始化。当我运行我的代码时,八条鱼永远不会出现。在某些情况下,一,二或三。但是当我调试代码时,会出现八条鱼。

我真的不知道发生了什么。希望你能帮我找到答案。

class Fish : Aquaticanimal   
{
    private int x;

    public int X
    {
        get { return x; }
        set { x = value; }
    }

    private int y;

    public int Y
    {
        get { return y; }
        set { y = value; }
    }

    public Fish(Bitmap fish,Form form)
    {
        quantity++;
        aquaticAnimal.BackColor = Color.Transparent;
        aquaticAnimal.Image = fish;
        aquaticAnimal.SizeMode = PictureBoxSizeMode.StretchImage;
        positioning(form);
    }

    private void positioning(Form form)
    {
        Random rnd = new Random();
        int FormWidth= Convert.ToInt32( form.Size.Width.ToString());
        int FormHeight = Convert.ToInt32(form.Size.Height.ToString());
        aquaticAnimal.Parent=form;
        aquaticAnimal.Top = rnd.Next(200, FormHeight - 100);
        aquaticAnimal.Left = rnd.Next(0, FormWidth - 100);
        this.x = aquaticAnimal.Top;
        this.y = aquaticAnimal.Left;
    }
}

private void Form1_Load(object sender, EventArgs e)
{
    Bitmap[] images = new Bitmap[8];
    images[0] = Pecera.Properties.Resources.Nemo;
    images[1] = Pecera.Properties.Resources.Pez_hembra;
    images[2] = Pecera.Properties.Resources.Pez_macho;
    images[3] = Pecera.Properties.Resources.tiburon_adulto;
    images[4] = Pecera.Properties.Resources.Tiburon_bebe_hembra;
    images[5] = Pecera.Properties.Resources.tiburon_macho;
    images[6] = Pecera.Properties.Resources.Dorys;
    images[7] = Pecera.Properties.Resources.tiburon_hembra;

    Fish[] fish = new Fish[8];
    for (int x = 0; x < 8; x++)
    {
        fish[x] = new Fish(images[x], this);
    }
}

1 个答案:

答案 0 :(得分:0)

这是一种非常快速地创建Random的新实例的情况,导致不那么随机的值。你的鱼彼此重叠,因为“随机”值是相同的。

您必须以仅使用Random的单个实例的方式重构代码。

这是我的建议,尽可能少地修改代码:

class Fish : Aquaticanimal
{
    ...
    ...

    private static Random rnd = new Random();

    private void positioning(Form form)
    {
        int FormWidth= Convert.ToInt32( form.Size.Width.ToString());
        int FormHeight = Convert.ToInt32(form.Size.Height.ToString());
        aquaticAnimal.Parent=form;
        aquaticAnimal.Top = rnd.Next(200, FormHeight - 100);
        aquaticAnimal.Left = rnd.Next(0, FormWidth - 100);
        this.x = aquaticAnimal.Top;
        this.y = aquaticAnimal.Left;
    }
}

FWIW,你的Fish课程真的不应该负责将自己定位在表格上。