Drawing a Sprite

Demonstrates how to draw a sprite by using the SpriteBatch class.

The Complete Sample

The code in this topic shows you the technique. You can download a complete code sample for this topic, including full source code and any additional supporting files required by the sample.

Download SpriteDemo_Sample.zip.

Drawing a Sprite

To draw a sprite on screen

  1. Derive a class from Game.

  2. Define a SpriteBatch object as a field on your game class.

  3. In your LoadContent method, construct the SpriteBatch object, passing the current graphics device.

  4. Load the textures that will be used for drawing sprites in LoadContent.

    In this case, the example uses the Content member to load a texture from the XNA Framework Content Pipeline. The texture must be in the project, with the same name passed to Load.

    private Texture2D SpriteTexture;
    private Rectangle TitleSafe;
    protected override void LoadContent()
        // Create a new SpriteBatch, which can be used to draw textures.
        spriteBatch = new SpriteBatch(GraphicsDevice);
        SpriteTexture = Content.Load<Texture2D>("ship");
        TitleSafe = GetTitleSafeArea(.8f);
  5. In the overridden Draw method, call Clear.

  6. After Clear, call Begin on your SpriteBatch object.

  7. Create a Vector2 to represent the screen position of the sprite.

    On Xbox 360, be careful not to draw foreground sprites on the outer 10 or 20 percent of the screen. Some televisions may obscure the edges of the screen. The GetTitleSafeArea function calculates the area of the current Viewport that is safe, given a specified safety percentage.

            protected Rectangle GetTitleSafeArea(float percent)
                Rectangle retval = new Rectangle(
    #if XBOX
                // Find Title Safe area of Xbox 360.
                float border = (1 - percent) / 2;
                retval.X = (int)(border * retval.Width);
                retval.Y = (int)(border * retval.Height);
                retval.Width = (int)(percent * retval.Width);
                retval.Height = (int)(percent * retval.Height);
                return retval;            
                return retval;
  8. Call Draw on your SpriteBatch object, passing the texture to draw, the screen position, and the color to apply.

  9. Use Color.White to draw the texture without any color effects.

  10. When all the sprites have been drawn, call End on your SpriteBatch object.

    protected override void Draw(GameTime gameTime)
        Vector2 pos = new Vector2(TitleSafe.Left, TitleSafe.Top);
        spriteBatch.Draw(SpriteTexture, pos, Color.White);

See Also


What Is a Sprite?