通过代码创建多个PictureBox-仅可见一个 [英] Creating numerous PictureBoxes by code - only one is visible

查看:88
本文介绍了通过代码创建多个PictureBox-仅可见一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用以下代码绘制图像的许多实例:

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.

我也尝试过使用以下代码在for循环中添加控件的方式有所不同(没有运气);

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

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

我有很多次这个问题,尤其是当我尝试以类似的方式创建许多GroupBox时.在尝试查找解决方案的过程中,我上网搜索的时间长达数小时,没有任何解决方案.

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.

推荐答案

您实际上只是在创建PictureBox的一个实例:

You're only actually creating one instance of PictureBox:

PictureBox mainSprite = new PictureBox();

...

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

您的数组将具有对同一对象的大量引用.您应该在循环的每次迭代中创建一个 new PictureBox:

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

这篇关于通过代码创建多个PictureBox-仅可见一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆