将不同的图像加载到不同的图片框中

时间:2014-05-18 16:45:15

标签: c# text-files picturebox

遇到这个问题。我有一个带有4个图片框的表单,当表单加载时我希望这4个图片框加载4个不同的图像形成文本文件。我是这样做的:

        optionOne.Image = new Bitmap(questionOne.getFoto(rand));

但是,如果我为所有m个图片框采用相同的代码行,只需将optionOne更改为optionTwo(我的第二个pictureBox),例如它只显示相同的图片。

我从像这样的文本文件中获取照片

      public string getFoto(int number)
    {
        stream = File.OpenText("Fotodd.txt");
        string[] fotos;
        string line = stream.ReadLine();
        fotos = line.Split('|');
        return fotos[number];
    }

我在文本文件中写了这样的内容:

    1.jpg | 2.jpg | 3.jpg | ...

那么如何使用文本文件在这些不同的pictureBox中加载不同的图像?

1 个答案:

答案 0 :(得分:1)

int fotoCounter = 1;
public string getFoto(int number)
    {
        string line;
        using (var sr = new StreamReader("Fotodd.txt"))
        {
            line = sr.ReadLine();
        }
        string[] fotos;
        fotos = line.Split('|');
        return fotos[number *  fotoCounter - 1].Trim(); // String.Trim() removes whitespaces
    }

并将其称为:

string name = pictureBox1.Name;
optionOne.Image = new Bitmap(questionOne.getFoto(Convert.ToInt32(name[name.Length - 1])));

name变量是获取pictureBox控件的编号;你必须使它更加动态,因为控件并不总是pictureBox1。如果您需要一点帮助,请提供之前的代码。 完成所有4个PictureBox控件的更新后,请增加fotoCounter。 我不明白为什么数组索引 - 1不起作用。数组使用从0开始的索引,这意味着如果你想获得第一张图片(1.jpg),它实际上是fotos [0]。

方法2:

string name = (PictureBox)Control.Name;
string number = Convert.ToInt32(name[name.Length - 1]) * fotoCounter;
string file = number + ".jpg";