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 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.
Download TiledSprite_Sample.zip.
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) { GraphicsDevice.Clear(Color.CornflowerBlue); Rectangle source = new Rectangle(0, 0, xna.Width * TilesX, xna.Height * TilesY);
spriteBatch.Begin(SpriteBlendMode.AlphaBlend, SpriteSortMode.Immediate, SaveStateMode.None); GraphicsDevice.SamplerStates[0].AddressU = TextureAddressMode.Wrap; GraphicsDevice.SamplerStates[0].AddressV = TextureAddressMode.Wrap;
Vector2 pos = new Vector2(50); spriteBatch.Draw(xna, pos, source, Color.White, 0, Vector2.Zero, 0.5f, SpriteEffects.None, 1.0f);
spriteBatch.End(); base.Draw(gameTime); }