如何在运行时在 XNA 中加载纹理?
我正在开发一个使用 XNA 框架进行 3D 渲染的应用程序。我现在想从文件加载纹理。到目前为止我发现了两种方法:
Texture2D.FromStream(GraphicsDevice, Stream)
这种方法的问题是它只加载 gif、png 和 jpg,而且我还需要对 tga 图像的支持。- 创建一个
ContentManager
对象。这种方法的问题在于,似乎所有纹理都需要静态添加到项目中,根据文档:“在 ContentManager 加载资源之前,您需要将资源添加到游戏项目中”。所讨论的程序是一个关卡编辑器,并且事先并不知道需要哪些纹理。
有没有其他简单的方法来加载纹理,我正在考虑使用其他一些类来加载图像(虽然我不知道是哪个,我对 C# 不太熟悉),然后也许使用 Texture2D.SetData 方法?
还有其他简单的方法可以实现我想要实现的目标吗?
I'm working on an application that uses the XNA framework to do it's 3D rendering. I now want to load a texture from file. I've found two methods so far:
Texture2D.FromStream(GraphicsDevice, Stream)
The problem with this approach is that it only loads gif, png and jpg and I also need support for tga images.- Create a
ContentManager
object. The problem with this approach is that it seems like all the textures need to be statically added to the project, from the documentation: "Before a ContentManager can load an asset, you need to add the asset to your game project". The program in question is a level editor and which textures are needed isn't known in advance.
Is there any other easy way to load the texture, I'm thinking about using some other class to load the image (although I don't know which, I'm not very familiar with C#) and then perhaps use the Texture2D.SetData
method?
Is there any other easy way to achieve what I'm trying to achieve?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
有几种方法可以实现您想要的效果:
您可以在编辑器中调用内容管道,动态创建内容项目。 WinForms Series 2 示例。这可能是“最好”的方式,因为它允许您继续使用内容管道。
正如您所说,您可以自己解码 TGA 文件并使用
SetData
。 Google 上有很多适合 C# TGA 读者的结果。 这是第一个。There are a few ways to achieve what you want:
You could invoke the content pipeline from within your editor, dynamically creating your content project. How to do this is described in the WinForms Series 2 Sample. This is probably the "best" way, because it allows you to keep using the content pipeline.
You could, as you say, decode the TGA file yourself and use
SetData
. There are lots of results for C# TGA readers on Google. This is the first one.我之前使用过
Texture2D.FromFile(device, path)
,效果很好。然而,偶尔我会遇到问题,并且还必须指定TextureCreationParameters
并将它们传递进去。请记住,您需要手动处理加载的 Texture2D。I've used
Texture2D.FromFile(device, path)
before, and it works well. However occasionally I'll encounter problems and will also have to specifyTextureCreationParameters
and pass them in. Keep in mind that you'll need to dispose the loaded Texture2D manually.