How To: Tile a Sprite

This article 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 tutorial illustrates the technique described in the text. A complete code sample for this tutorial is available for you to download, including full source code and any additional supporting files required by the sample.

To Draw a Tiled Sprite on Screen

  1. Follow steps 1–4 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, choosing SpriteSortMode.Immediate. Then 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;
  4. 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);
  5. When all of the sprites have been drawn, call End on your SpriteBatch object.

Community Additions