Table of Contents

Tiling a Sprite

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

Overview

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.

We will simply define an area (Rectangle) in which to draw our texture, but in a SpriteBatch drawing mode that will keep tiling the texture until it fills the area.

End result

The output of this tutorial

Requirements

Sprite to Tile

Drawing a Tiled a Sprite

  1. Follow the procedures of Drawing a Sprite.

  2. Setup some new variables to define how we want to draw the tiled area and with which Texture.

    // Tiling Texture
    private Texture2D monoGameLogo;
    // How many tiles wide
    private int tileCountWidth = 2;
    // How many tiles high
    private int tileCountHeight = 2;
    // Rectangle to draw tiles in
    private Rectangle targetRectangle;
    // Position to draw the tiled Rectangle at
    private Vector2 position;
    
    
  3. In the LoadContent method, we will load the Texture and then setup our drawing position and target based on the input graphics dimensions. Feel free to play with these values to alter how the tiling area is drawn.

    // Load the texture to tile.
    monoGameLogo = Content.Load<Texture2D>("MonoGame");
    
    // Define a drawing rectangle based on the number of tiles wide and high, using the texture dimensions.
    targetRectangle = new Rectangle(0, 0, monoGameLogo.Width * tileCountWidth, monoGameLogo.Height * tileCountHeight);
    
    // Get the drawable area of the screen.
    Viewport viewport = GraphicsDevice.Viewport;
    
    // Center the rectangle on the screen, using both the screen center and the rectangle center.
    position = new Vector2(-targetRectangle.Width / 2 + viewport.Width / 2, -targetRectangle.Height / 2 + viewport.Height / 2);   
    
  4. In the Game.Draw method, call SpriteBatch.Begin to set the sprite state.

    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.

    The Begin method is also using overrides to define the SamplerState and set it to Wrap (repeat).

    _spriteBatch.Begin(SpriteSortMode.FrontToBack, BlendState.Opaque, SamplerState.LinearWrap,
        DepthStencilState.Default, RasterizerState.CullNone);
    
  5. Call SpriteBatch.Draw with the sprite, the destination rectangle, and other relevant parameters.

    _spriteBatch.Draw(monoGameLogo, Vector2.Zero, targetRectangle, Color.White, 0, Vector2.Zero, 1, SpriteEffects.None, 0);
    
  6. Call SpriteBatch.End on your SpriteBatch object.

    _spriteBatch.End();
    

See Also

Concepts

Reference

© 2012 Microsoft Corporation. All rights reserved.