如何在类中具有存储图片/图像的属性? [英] How can I have a property in a class to store an picture/image?
问题描述
我希望我的Hero类中的一个属性具有用于其图像的Portrait属性.在这种情况下应该使用哪种对象类型?
I want a attribute in my Hero class to have a Portrait attribute for his/her image. What object type should I use in this case?
public class Hero
{
public string Name { get; set; }
public string HeroType { get; set; }
public int StartingHP { get; set; }
public int StartingMana { get; set; }
public Dictionary<string, string> Spells { get; set; }
public Dictionary<string, string> Items { get; set; }
}
推荐答案
In WPF, you should use the ImageSource
class, like this:
public class Hero {
public string Name { get; set; }
public string HeroType { get; set; }
public int StartingHP { get; set; }
public int StartingMana { get; set; }
public Dictionary<string, string> Spells { get; set; }
public Dictionary<string, string> Items { get; set; }
public ImageSource Portrait { get; set; }
}
您可以从这样的文件中读取图像:
You can read an image from a file like this:
myHero.Portrait = new BitmapImage(new Uri(filePath, UriKind.Absolute));
您可以使用 Image
System.Drawing.dll中的类.例如:
You can use the Image
class from System.Drawing.dll. For example:
public class Hero {
public string Name { get; set; }
public string HeroType { get; set; }
public int StartingHP { get; set; }
public int StartingMana { get; set; }
public Dictionary<string, string> Spells { get; set; }
public Dictionary<string, string> Items { get; set; }
public Image Portrait { get; set; }
}
要加载图像,请调用Image.FromFile(path)
.如果流中有图像(例如,来自数据库或Web服务的图像),则可以调用Image.FromStream(stream)
.
To load the image, call Image.FromFile(path)
. If you have an image in a stream (eg, from a database or web service, you can call Image.FromStream(stream)
.
如果在编译时拥有所有图像,则可以将它们放在ResX文件中;否则,可以将它们放置在ResX文件中.您可以从设计师生成的代码文件中获取图像,如下所示:myHero.Portrait = SomeResXFile.Portrait1
.
If you have all of the images at compile time, you can put them in a ResX file; you can get an image from the designer-generated code file like this: myHero.Portrait = SomeResXFile.Portrait1
.
这篇关于如何在类中具有存储图片/图像的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!