Creating numerous PictureBoxes by code - only one is visible

前端 未结 1 1019
悲哀的现实
悲哀的现实 2021-01-27 23:47

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, Ev         


        
相关标签:
1条回答
  • 2021-01-28 00:28

    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;
        ...
    }
    
    0 讨论(0)
提交回复
热议问题