Xna: Load Texture2D from Embedded Resource

If you’re writing an app which uses Xna, you may need to load a texture from an embedded resource. Here’s how:

First embed the resource in your app. Do so by choosing Embedded Resource as the Build Action in the properties of the resource.

Properties Dialog for a File

After that you can load the Texture2D using a stream handle to the embedded file.

Stream stream = Assembly.GetCallingAssembly().GetManifestResourceStream("AppNamespace.Folder.font.bmp");
return Texture2D.FromFile(graphicsDevice, stream);

GetCallingAssembly() can be exchanged with GetExecutingAssembly() if needed. The name of the resource must be fully qualified with the app’s namespace and folders. I usually keep my resources in a folder Resources so I would have: AppNamespace.Resources.font.bmp.

500 Downloads of the Same Game

My little Xna game that I wrote nearly 2 years ago reached the 500 downloads mark (binaries and source) the other day. With that said, I’d like to say that I’m working on version 2.0.

In version 2.0 I’m going to make the code more event driven. The old code uses the Xna Game class and in the new version I’ll be making it WinForms based. Almost a complete rewrite.

My work so far is available through SVN on the project’s Codeplex page.

Drawing Rectangles with SpriteBatch

Just a quick code snippet which adds an extension method for drawing Rectangles to SpriteBatch:

public static class SpriteBatchHelper
{
	static Texture2D pixel;

	private static void LoadPixel(GraphicsDevice graphicsDevice)
	{
		if(pixel == null)
		{
			pixel = new Texture2D(graphicsDevice, 1, 1);
			pixel.SetData<Color>(new Color[] { Color.White });
		}
	}

	public static void DrawRectangle(this SpriteBatch spriteBatch, Rectangle rectangle, Color color)
	{
		LoadPixel(spriteBatch.GraphicsDevice);
		spriteBatch.Draw(pixel, rectangle, color);
	}
}

Creating and consuming services in your XNA Game

The GameServiceContainer implements the IServiceProvider interface and the MSDN documentation says about the IServiceProvider interface:

Defines a mechanism for retrieving a service object; that is, an object that provides custom support to other objects.

This article will “attempt” to describe how can you use the GameServiceContainer in your XNA game, in both your GameComponent(s) and your game’s entity objects.
Continue reading

First Look at Map Editor

MapEditor

I’ve been working on a map editor for what seem likes forever now. I’ve gotten so much done and then I would just feel like the thing was written poorly and so I would completely reorganize it. I’ve done that about 3 times now.

Finally though I have an MVC pattern going in the code and I’m very comfortable with what I’ve written. I’m not sure when I’ll be finished but I should have something workable within the next weeks or so.