How do I load a texture in XNA at runtime?
Asked Answered
S

2

9

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:

  1. 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.
  2. 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?

Sirocco answered 16/8, 2010 at 16:25 Comment(0)
I
3

There are a few ways to achieve what you want:

  1. 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.

  2. 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.

Ifc answered 17/8, 2010 at 5:10 Comment(0)
R
2

I've used Texture2D.FromFile(device, path) before, and it works well. However occasionally I'll encounter problems and will also have to specify TextureCreationParameters and pass them in. Keep in mind that you'll need to dispose the loaded Texture2D manually.

Rota answered 16/8, 2010 at 19:48 Comment(2)
FromFile was replaced with FromStream in XNA 4.0. Given that the OP is using FromStream, they probably want an XNA 4.0-compatible answer.Ifc
Why does it need to be disposed of manually? Is it because it's not using the content loader?Curvilinear

© 2022 - 2024 — McMap. All rights reserved.