How to load texture into XNA at runtime?

I am working on an application that uses the XNA framework for 3D rendering. Now I want to load a texture from a file. So far I have found two methods:

  • Texture2D.FromStream(GraphicsDevice, Stream) The problem with this approach is that it only loads gif, png and jpg, and I also need tga image support.
  • Create a ContentManager object. The problem with this approach is that it seems that all textures should be statically added to the project from the documentation: "Before the ContentManager can load the object, you need to add the asset to your game project." This program is a level editor and what textures are needed is not known in advance.

Is there any other easy way to load a texture, I'm thinking of using some other class to load an image (although I don't know what, I'm not very familiar with C #), and then maybe the Texture2D.SetData method?

Is there any other easy way to achieve what I am trying to achieve?

+7
c # xna
source share
2 answers

There are several ways to achieve the desired result:

  • You can call the content pipeline from your editor by dynamically creating your content project. How to do this is described in WinForms Series 2 Sample . This is probably the β€œbest” way as it allows you to continue using the content pipeline.

  • You could, as you say, decode the TGA file yourself and use SetData . For C # TGA readers, Google has many results. This is the first option .

+3
source share

I have used Texture2D.FromFile(device, path) before and it works well. However, sometimes I run into problems and also have to specify TextureCreationParameters and pass them. Keep in mind that you need to manually download the downloaded Texture2D.

+2
source share

All Articles