How To: Tile a Sprite
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
- Follow steps 1–4 of How To: Draw a Sprite.
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.
- Call SpriteBatch.Begin, choosing SpriteSortMode.Immediate. Then set the TextureAddressMode of the first SamplerState to TextureAddressMode.Wrap for both the u and v directions.
- Call SpriteBatch.Draw with the sprite to tile, the starting position of the sprite, the source rectangle you created, and other relevant parameters.
- When all of the sprites have been drawn, call End on your SpriteBatch object.