Tuesday, August 23, 2011

An easy way to create 1x1 textures for XNA.


I've noticed on more than a few occasions while reviewing XNA code for demos and game engines that people often need small textures in order to render diagnostic information. More often than not, they will create a small bitmap file and feed it through the content pipeline. It's no big deal, but there is a slightly easier way that is also better performing - just create a 1x1 texture directly, without using the file system.

Here's a function that does just that:


public static Texture2D CreateSolidTexture(GraphicsDevice graphics, Color color)
{
	var tex = new Texture2D(graphics, 1, 1, falseSurfaceFormat.Color);
	tex.SetData<Color>(new Color[] { color });
	return tex;
}
As a bonus, anyone using your demo, engine or what have you will have a slightly easier time using your code because they won't have to deal with migrating the sample content into their code space.