Creating numerous PictureBoxes by code - only one is visible

不想你离开。 提交于 2019-12-02 19:58:53

问题


I am trying to draw lots of instances of an image using the following code:

PictureBox[] sprites = new PictureBox[100];

private void Game_Load(object sender, EventArgs e)
{
    PictureBox mainSprite = new PictureBox();
    Bitmap img = new Bitmap(SpriteTest.Properties.Resources.Image); //Load a png image

    mainSprite.Size = new Size(16, 16);
    mainSprite.Image = img;

    for(var i = 0; i < sprites.Length; i++)
    {
        sprites[i] = mainSprite;

        //Keeping it simple for now with a single row of sprites
        sprites[i].Location = new Point(i * 16, 8); 
    }

    Game.ActiveForm.Controls.AddRange(sprites);
}

When it comes to running the code, only the last image is shown. While debugging the code, everything seems to be working as expected. I can also verify that the location is in fact being updated.

I have also tried adding the controls differently using the following code in the for loop (with no luck);

this.Controls.Add(sprites[i]);

I have had this problem many times, especially when I tried to create many GroupBoxes in a similar fashion. For the hours that I searched online as I tried to find a solution, nothing has ever fixed it.


回答1:


You're only actually creating one instance of PictureBox:

PictureBox mainSprite = new PictureBox();

...

for(var i = 0; i < sprites.Length; i++)
{
    sprites[i] = mainSprite;

Your array will have lots of reference to the same object. You should create a new PictureBox on each iteration of the loop:

for(var i = 0; i < sprites.Length; i++)
{
    PictureBox mainSprite = new PictureBox();
    mainSprite.Size = new Size(16, 16);
    mainSprite.Image = img;
    sprites[i] = mainSprite;
    ...
}


来源:https://stackoverflow.com/questions/6606819/creating-numerous-pictureboxes-by-code-only-one-is-visible

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!