正在显示pictureBox数组

本文关键字:数组 pictureBox 显示 | 更新日期: 2024-09-23 05:56:20

我想显示13个pictureBox,但它最终只显示最后一个。所以我想知道我是不是做错了。

以下代码从resources文件夹中获取图像。

var testP = new PictureBox();
for (int i = 0; i < 13; i++)
{
    testP.Width = 65;                                   
    testP.Height = 80;
    testP.BorderStyle = BorderStyle.None;
    testP.SizeMode = PictureBoxSizeMode.StretchImage;
    test[i] = getImage(testP, testPTemp[i]);              
}

以下代码试图显示位置发生变化的13 pictureBox。

这两个代码段应该能够执行该操作。

test = new PictureBox[13];    
for (var i = 0; i < 13; i++)
{
    test[i].Image = (Image)Properties.Resources.ResourceManager.GetObject("_" + testTemp[i]);    
    test[i].Left = 330;      
    test[i].Top = 500;      
    test[i].Location = new Point(test[i].Location.X + 0 * displayShift, test[i].Location.Y);  
    this.Controls.Add(test[i]);
}

这是getImage()

private PictureBox getImage(PictureBox pB, string i)               // Get image based on the for loop number (i)
    {
        pB.Image = (Image)Properties.Resources.ResourceManager.GetObject("_" + i);           // Get the embedded image
        pB.SizeMode = PictureBoxSizeMode.StretchImage;
        return pB;
    }

正在显示pictureBox数组

我很确定有所有的PictureBox控件,但它们都有相同的位置,所以它们位于彼此之上。这就是为什么你只能看到最后一个。

我认为应该将0替换为I变量。

test[i].Location = new Point(test[i].Location.X + i * displayShift, test[i].Location.Y); this.Controls.Add(test[i]); 

根据您提供的代码很难判断出确切的问题。一个可能的问题是,当您创建PictureBoxes时,您只在for循环之前创建一个实例,然后用对该实例的引用填充数组。另一种可能性是,当你计算控件的X位置时,你要乘以0,这将总是得到0(意味着所有控件都在位置330)。

下面的代码将基本上实现您正在尝试的内容,但如果没有您所有的代码,我无法给您一个更具体的示例。

在您的班级

const int PICTURE_WIDTH = 65;
const int PICTURE_HEIGHT = 85;

内部功能

//Loop through each image
for(int i = 0; i < testTemp[i].length; i++)
{
    //Create a picture box
    PictureBox pictureBox = new PictureBox();
    pictureBox.BorderStyle = BorderStyle.None;
    pictureBox.SizeMode = PictureBoxSizeMode.StretchImage;
    //Load the image date
    pictureBox.Image = (Image)Properties.Resources.ResourceManager.GetObject("_" + testTemp[i]);
    //Set it's size
    pictureBox.Size = new Size(PICTURE_WIDTH, PICTURE_HEIGHT);
    //Position the picture at (330,500) with a left offset of how many images we've gone through so far
    pictureBox.Location = new Point(330 + (i * PICTURE_WIDTH), 500);
    //Add the picture box to the list of controls
    this.Controls.Add(pictureBox);
}

如果您需要保留图片框的列表,只需在循环之前创建一个新列表,并将每个pictureBox添加到循环内的列表中。如果要将这些PictureBox添加到的控件/窗口需要向左或向右滚动以查看所有图像,请将AutoScroll属性设置为true