Developing Game-Themed Applications with XNA Game Studio

Day 1 - Section I: Introduction and Overview
c. Drawing with XNA

back to Day-1 main page


References:

Goals:

Notice:


The result: If you compile and run the given source code, you will see:
Notice the Microsoft logo. We will examine how to draw this logo in this tutorial.


Implementation:
  1. The image: refer to the UsefulFile folder, there is an image by the name of MS.jpg in this folder. This is the Microsoft logo:
  2. In order for us to use this image in our application we must first include this image as part of our XNA GS project.

  3. Using the image:
    1. Source code: download the template source code (from 1b) and unzip.
    2. Start the XNA GS IDE, in the solution explorer, Right Mouse Click under
      Content->Add->Existing Item ...
      Navigate to the UsefulFile folder and select the MS.jpg file.

  4. Source code:
  5. We have added code to the Game1.cs file of the simple default project at 3 separate places:

    1. Instance variables: for representing the image (as a texture).
    2. LoadContent(): load the image file as a texture into our program.
    3. Draw():  draw the texture image.

    Here are the details, each of the following changes are enclosed by regions with label: __CODE_ADDED__:

    1. Declare new instance variables (in the beginning of the file) for drawing support:
      #region __CODE_ADDED__: instance variable for the image and its position
         
      Texture2D sprite;   // represent the image as a 2D texture
      #endregion

    2. Load the image (in LoadContent() function):

      #region __CODE_ADDED__: load the image
         sprite = Content.Load<Texture2D>("MS");

                      // Notice: do not specify the ".jpg"

      #endregion


    3. Draw a triangle (in Draw() function):

      #region __CODE_ADDED__: draw the image as a sprite (2D Texture)
         spriteBatch.Begin();          
      // Get ready to draw
         spriteBatch.Draw(sprite, ...);
      // draw the image
         spriteBatch.End();  
                // Present the result to the screen

      #endregion

Notice that:
  1. We did not specify the size of the MS.jpb image. The size is
  2. pre-determined for us.


  3. Drawing is done in pixel space.

This document and the related materials are developed with support from Microsoft Research Computer Gaming Initiative under the Computer Gaming Curriculum in Computer Science RFP, Award Number 15871, and 16531.


Kelvin Sung
Computing and Software Systems
University of Washington, Bothell
ksung@u.washington.edu