Tiling a Sprite

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

Bb975153.graphics_sprite_tiled(en-us,XNAGameStudio.41).jpg

This sample uses a texture addressing mode to duplicate a texture across the area defined by SpriteBatch.Draw. 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.

Download TiledSprites_Sample.zip.

Tiling a Sprite

To tile a sprite

  1. Follow the procedures of Drawing a Sprite.

  2. In the Draw method, create a Rectangle to define the area to fill.

    The destination Rectangle can be any size. In this example, the width and height of the destination rectangle are integer multiples of the source sprite. This will cause the sprite texture to be tiled, or drawn several times, to fill the destination area.

    spriteBatch.Begin(SpriteSortMode.FrontToBack, BlendState.Opaque, SamplerState.LinearWrap,
        DepthStencilState.Default, RasterizerState.CullNone);
    
  3. Call SpriteBatch.Begin to set the sprite state.

  4. Set the TextureAddressMode in the SamplerState to TextureAddressMode.LinearWrap.

    spriteBatch.Draw(spriteTexture, Vector2.Zero, destRect, color, 0, Vector2.Zero, 1, SpriteEffects.None, 0);
    
  5. Call SpriteBatch.Draw with the sprite, the destination rectangle, and other relevant parameters.

  6. Call End on your SpriteBatch object.

    spriteBatch.End();
    

See Also

Tasks

Drawing a Sprite

Concepts

What Is a Sprite?

Reference

SpriteBatch
Draw
SpriteSortMode
Texture2D