【问题标题】:Using PictureBox in Visual Studio在 Visual Studio 中使用 PictureBox
【发布时间】:2013-07-22 11:20:51
【问题描述】:

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

pictureBox1.Image = Properties.Resources.Desert;

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

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

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

【问题讨论】:

    标签: c# visual-studio picturebox


    【解决方案1】:

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

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

    【讨论】:

    • 非常感谢您的努力。如果可以,什么是“kvp”?
    • 我将其命名为kvp,因为它代表“键值对”。一个字典项。
    【解决方案2】:

    看看这个:Programatically using a string as object name when instantiating an object。默认情况下,C# 不允许您这样做。但是您仍然可以使用string 从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");
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-05
      • 2012-05-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-08
      • 2018-04-15
      • 1970-01-01
      相关资源
      最近更新 更多