XNA and GIS (2) – Using Textures

March 25th, 2007

As mentioned in our previous post, XNA offers a graphical framework to build some cool mapping applications. We will first discuss several coding techniques as it relates to our objectives before building an actual XNA program. For more general XNA tutorials, I encourage you to see some of the sites discussed in the last post.

Open Visual C# Express (after installing the XNA Game Studio Express) and create a new Windows Game. The new project comes with all of the base XNA code already setup in several functions. In fact, you can go ahead and press F5 to compile and run the program right away. A form should display with a light blue background.

Back to the code, here is the structure of the XNA template in the Game1.cs file:

XNA_Template

As you can see, within the Game1 class there is 1 constructor and 5 additional functions. Here is how and/or where to put some additional code we will need to create our mapping applications.

Changing the size of the form

A common first task is to change the size of the form. In the Initialize function, add this code to change the size to 400 by 200 pixels:

 

graphics.PreferredBackBufferWidth = 400;
graphics.PreferredBackBufferHeight = 200;
graphics.ApplyChanges();

 

Displaying full-screen graphics will be discussed later.

Loading Textures

Textures are building blocks of any graphics program. These 2D images can be used in a variety of situations in mapping applications. For example, multiple textures could be “tiled” to display a background map similar to Google Maps. Textures could also be used to draw map tools and other buttons in an interface on top of a map.

Textures in XNA are created like this:

 

Texture2D t2dWorldMap;
t2dWorldMap = content.Load("WorldMap");

 

In that code, the source texture (“WorldMap”) was loaded using the XNA Framework Content Pipeline. To load a texture directly from a file:

 

t2dWorldMap = Texture2D.FromFile(graphics.GraphicsDevice,
 @"../../../WorldMap.png");

 

Drawing Textures

Textures can be drawn as 2D sprites using the SpriteBatch class in the Draw function:

 

spriteBatch.Begin(SpriteBlendMode.AlphaBlend);
spriteBatch.Draw(t2dWorldMap, new Rectangle(0, 0, 400, 200), Color.White);
spriteBatch.End();

 

Understanding how to use textures in XNA is probably the most important concept when creating mapping programs. To get a sense of where we are heading, check out this more advanced XNA sample on texture tiling.

Continue to part 3