图片框c#中的图像
本文关键字:图像 | 更新日期: 2023-09-27 17:58:28
我正在编写一个程序,在picturebox中尝试不同的图像,但图像必须与文本相对应。此外,它必须来自项目的"资源"文件夹。
这就是我想做的,如果文本"苹果"显示在屏幕上,那么文件名为"苹果"的图像也会显示在picturebox中。。
我可以像这个一样在"if else"中完成
string word="apple";
if(word==apple)
pictureBox1.Image= WindowsFormsApplication4.Properties.Resources.apple;
但是如果我有一千张照片,我仍然认为有一个简单的方法,。。
我在试这个,
string word=label1.Text;//label1.text changes from time to time
pictureBox1.Image= WindowsFormsApplication4.Properties.Resources.word;
但我知道"单词"是字符串。。。。这是不可能的。。。我无法将字符串附加到语法。。。。
您可以使用ResourceManager类的GetObject
方法传入字符串:
string itemName = label1.Text;
this.pictureBox1.Image =
(Image)Properties.Resources.ResourceManager.GetObject(itemName);
如果您打开资源.Designer.cs
文件代码,您将看到类似以下内容:
internal static System.Drawing.Bitmap apple {
get {
object obj = ResourceManager.GetObject("apple", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
所以你可以做同样的事情:
string word=label1.Text;//label1.text changes from time to time
pictureBox1.Image= (System.Drawing.Bitmap)WindowsFormsApplication4
.Properties
.Resources
.ResourceManager.GetObject(word);