我想像这样加载图像:
void info(string channel)
{
//Something like that
channelPic.Image = Properties.Resources.+channel
}
因为我不想做
void info(string channel)
{
switch(channel)
{
case "chan1":
channelPic.Image = Properties.Resources.chan1;
break;
case "chan2":
channelPic.Image = Properties.Resources.chan2;
break;
}
}
这样的事情可能吗?
您始终可以使用
System.Resources.ResourceManager
来返回此类使用的缓存 ResourceManager
。由于 chan1
和 chan2
代表两个不同的图像,因此您可以使用 System.Resources.ResourceManager.GetObject(string name)
它返回与您的输入与项目资源相匹配的对象
示例
object O = Resources.ResourceManager.GetObject("chan1"); //Return an object from the image chan1.png in the project
channelPic.Image = (Image)O; //Set the Image property of channelPic to the returned object as Image
注意:如果在项目资源中找不到指定的字符串,
Resources.ResourceManager.GetObject(string name)
可能会返回null
。
谢谢,
我希望你觉得这有帮助:)
ResourceManager
: 来完成此操作
public bool info(string channel)
{
object o = Properties.Resources.ResourceManager.GetObject(channel);
if (o is Image)
{
channelPic.Image = o as Image;
return true;
}
return false;
}
在 WPF 中试试这个
StreamResourceInfo sri = Application.GetResourceStream(new Uri("pack://application:,,,/WpfGifImage001;Component/Images/Progess_Green.gif"));
picBox1.Image = System.Drawing.Image.FromStream(sri.Stream);
ResourceManager
将起作用。如果它只是您项目中的一个文件(假设是根目录),您可以使用如下方式获取它:
System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();
System.IO.Stream file = assembly .GetManifestResourceStream("AssemblyName." + channel);
this.pictureBox1.Image = Image.FromStream(file);
或者如果您使用 WPF:
private ImageSource GetImage(string channel)
{
StreamResourceInfo sri = Application.GetResourceStream(new Uri("/TestApp;component/" +
channel, UriKind.Relative));
BitmapImage bmp = new BitmapImage();
bmp.BeginInit();
bmp.StreamSource = sri.Stream;
bmp.EndInit();
return bmp;
}
this.toolStrip1 = new System.Windows.Forms.ToolStrip();
this.toolStrip1.Location = new System.Drawing.Point(0, 0);
this.toolStrip1.Name = "toolStrip1";
this.toolStrip1.Size = new System.Drawing.Size(444, 25);
this.toolStrip1.TabIndex = 0;
this.toolStrip1.Text = "toolStrip1";
object O = global::WindowsFormsApplication1.Properties.Resources.ResourceManager.GetObject("best_robust_ghost");
ToolStripButton btn = new ToolStripButton("m1");
btn.DisplayStyle = ToolStripItemDisplayStyle.Image;
btn.Image = (Image)O;
this.toolStrip1.Items.Add(btn);
this.Controls.Add(this.toolStrip1);
您可以在项目中添加图像资源,然后(右键单击项目并选择Properties项)以这种方式访问:
this.picturebox.image = projectname.properties.resources.imagename;