How To: Tile a Sprite

Demonstrates how to draw a sprite repeatedly in the x and y directions in one Draw call.

This sample takes advantage of the texture addressing modes of the graphics card to duplicate a texture across the area defined for drawing by SpriteBatch.Draw. Using SpriteSortMode.Immediate allows us to set the TextureAddressMode directly and enable wrapping. Other address modes (such as mirroring) can create interesting results.

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.

Drawing a Tiled Sprite

To draw a tiled sprite on screen

  1. Follow the procedures of How To: Draw a Sprite.
  2. In the Draw method, create a Rectangle, defining how many pixels to fill with your sprite's image.

    The total width of the Rectangle should be the number of times to tile your sprite in the x direction multiplied by the width of the sprite. The total height of the Rectangle should be the number of times to tile your sprite in the y direction multiplied by the height of the sprite.

    int TilesX = 2;
    int TilesY = 2;
    protected override void Draw(GameTime gameTime)
        Rectangle source = new Rectangle(0, 0, xna.Width * TilesX, xna.Height * TilesY);
  3. Call SpriteBatch.Begin, and then select SpriteSortMode.Immediate.

  4. Set the TextureAddressMode of the first SamplerState to TextureAddressMode.Wrap for both the u and v directions.

    spriteBatch.Begin(SpriteBlendMode.AlphaBlend, SpriteSortMode.Immediate, SaveStateMode.None);
    GraphicsDevice.SamplerStates[0].AddressU = TextureAddressMode.Wrap;
    GraphicsDevice.SamplerStates[0].AddressV = TextureAddressMode.Wrap;
  5. Call SpriteBatch.Draw with the sprite to tile, the starting position of the sprite, the source rectangle you created, and other relevant parameters.
    Vector2 pos = new Vector2(50);
    spriteBatch.Draw(xna, pos, source, Color.White, 0, Vector2.Zero, 0.5f, SpriteEffects.None, 1.0f);
  6. When all of the sprites have been drawn, call End on your SpriteBatch object.