我正在尝试获取一组 PictureBox
来显示图片列表(以 png 文件格式)。
我尝试使用 .NET ImageList
控件,但它坚持要重新调整我的图片大小。它也不支持那些 png 文件的透明背景。
我还尝试使用 Assembly
来检索我的文件,如下所示:
_imageStream = _assembly.GetManifestResourceStream("MyNamespace.MyImage.png");
但是代码没有返回任何资源文件,也没有抛出任何运行时错误。
我的问题是,还有其他方法可以做到这一点吗?或者更好的是,我能否以某种方式使 ImageList
控件不改变我的图片?谢谢。
最佳答案
你可以尝试这样的事情,虽然我不确定这是否是最好的:-
Assembly ambly = Assembly.LoadFile(pathToDll);
或
BitMap bitMap;
// where "ns" is the default namespace of the resource project
using (Stream resourceStream = ambly.GetManifestResourceSream("ns.image.jpg"))
{
bitMap = BitMap.FromStream(resourceStream);
}
一个例子:-
interface IThemeResourceProvider
{
Stream LoadBigLogo();
Stream LoadSmallLogo();
}
然后在你的资源库中实现那个接口(interface)
public class ThemeResourceProvider : IThemeResourceProvider
{
public Stream LoadBigLogo()
{
Assembly ambly = Assembly.GetExecutingAssembly();
return ambly.GetManifestResourceStream("namespace.image.jpg");
}
(...)
}
最后,不是直接在主应用程序中加载资源,而是实例化在资源库中找到的 IThemeResourceProvider
Assembly assembly = Assembly.LoadFile(pathToDll);
var results = from type in assembly.GetTypes()
where typeof(IThemeResourceProvider).IsAssignableFrom(type)
select type;
现在您在该列表中有一个 IEnumerable。通常,您只有一个,但使用这种方法,您还可以托管多组资源,并在同一个资源 dll 中实现多个 IThemeResourceProvider。你可以例如使用名称标识每个 IThemeResourceProvider,可以作为属性,也可以在各种实现上使用自定义 [Attribute] 修饰。我会把剩下的留给你自己解决。
但这里是如何实例化列表中的 IThemeResourceProviders
foreach (var providerType in results)
{
var constructorInfo = providerType.GetConstructor(Type.EmptyTypes);
IThemeResourceProvider provider = constructorInfo.Invoke(null);
}
最后,使用这些提供程序之一获取位图:
BitMap bitMap;
using (Stream resourceStream = provider.LoadBigLogo())
{
bitMap = BitMap.FromStream(resourceStream);
}
关于c# - 存储项目相关图片的好方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13296137/