2

我目前正在使用以下代码将图像加载到图片框。

pictureBox1.Image = Properties.Resources.Desert;

我将用“变量”替换“沙漠”,因为代码将按如下方式工作。

String Image_Name;
Imgage_Name = "Desert";
pictureBox1.Image = Properties.Resources.Image_Name;

我有很多需要加载的想象,并希望使用变量作为图像名称,而不必为每个图像编写单独的行。这可能吗 ?

4

2 回答 2

2

您可以遍历资源.. 像这样:

using System.Collections;

string image_name = "Desert";

foreach (DictionaryEntry kvp in Properties.Resources.ResourceManager.GetResourceSet(CultureInfo.CurrentCulture, true, true)) {
    if ((string)kvp.Key == image_name) {
        var bmp = kvp.Value as Bitmap;
        if (bmp != null) {
            // bmp is your image
        }
    }
}

您可以将它包装在一个不错的小函数中.. 像这样:

public Bitmap getResourceBitmapWithName(string image_name) {
    foreach (DictionaryEntry kvp in Properties.Resources.ResourceManager.GetResourceSet(CultureInfo.CurrentCulture, true, true)) {
        if ((string)kvp.Key == image_name) {
            var bmp = kvp.Value as Bitmap;
            if (bmp != null) {
                return bmp;
            }
        }
    }

    return null;
}

用法:

var resourceBitmap = getResourceBitmapWithName("Desert");
if (resourceBitmap != null) {
    pictureBox1.Image = resourceBitmap;
}
于 2013-07-22T03:16:54.840 回答
1

检查一下:实例化对象时以编程方式使用字符串作为对象名称。默认情况下,C# 不允许您这样做。但是您仍然可以使用 astring从 a 访问您想要的图像Dictionary

你可以尝试这样的事情:

Dictionary<string, Image> nameAndImg = new Dictionary<string, Image>()
{
    {"pic1",  Properties.Resources.pic1},
    {"pic2",  Properties.Resources.pic2}
    //and so on...
};

private void button1_Click(object sender, EventArgs e)
{
    string name = textBox1.Text;

    if (nameAndImg.ContainsKey(name))
        pictureBox1.Image = nameAndImg[name];

    else
        MessageBox.Show("Inavlid picture name");
}
于 2013-07-22T03:15:21.460 回答