我目前正在使用以下代码将图片加载到图片框中。
pictureBox1.Image = Properties.Resources.Desert;
我会用“变量”替换“沙漠”,因为代码的工作原理如下。
String Image_Name;
Imgage_Name = "Desert";
pictureBox1.Image = Properties.Resources.Image_Name;
我有很多想象,我需要加载并想要使用变量作为图像名称,而不必为每个图像写一个单独的行。这可能吗 ?
答案 0 :(得分: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;
}
答案 1 :(得分:1)
检查出来: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");
}