O'Reilly logo

Learning XNA 4.0 by Aaron Reed

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Loading and Drawing Your Sprite

Now that you have an image loaded into your solution that is recognized by the content pipeline, you’re ready to draw it on the screen. But before you can access them in code, resources need to be loaded from the content pipeline into variables that you can use to manipulate them.

The default object used to store an image is Texture2D. Go ahead and add a Texture2D variable to your game in the Game1.cs file near the variable declarations for your GraphicsDeviceManager and SpriteBatch:

Texture2D texture;

Now you’ll need to load the actual image file into your Texture2D variable. To access data from the content pipeline, you use the Content property of the Game class. This property is of the type ContentManager and provides access to all objects loaded in the content pipeline. The ContentManager class has a Load method that will let you load content into different XNA object formats.

As mentioned previously, all loading of graphics, sounds, and other content resources should be done within the LoadContent method. Add the following line to the LoadContent method:

texture = Content.Load<Texture2D>(@"Images/logo");

The parameter passed into the Content.Load method is the path to the image file, starting with the Content node in Solution Explorer. When used in relation to strings, the @ symbol causes the string that follows to be interpreted literally, with escape sequences ignored. So, the following two lines of code will create the exact same string:

string str1 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required