在Visual Studio中使用PictureBox

本文关键字:PictureBox Visual Studio | 更新日期: 2023-09-27 18:24:05

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

pictureBox1.Image = Properties.Resources.Desert;

我会将"Desert"替换为"Variable",因为代码的工作方式如下。

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

我有很多Imagine需要加载,并且希望使用一个Variable作为图像名称,而不必为每个图像单独写一行。这可能吗?

在Visual Studio中使用PictureBox

您可以对资源进行迭代。。像这样的东西:

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

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

你可以试试这样的东西:

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");
}