How To: Draw a Masked Sprite over a Background

This article demonstrates how to draw a foreground and background sprite using the SpriteBatch class, where only part of the foreground sprite masks the background. The foreground sprite in this example must include masking information.

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 foreground and background sprite

  1. Create the game class, and load resources as described in steps 1 and 2 of How To: Draw a Sprite.
  2. Instead of creating one SpriteBatch object, create two—one for the foreground sprites, and one for the background sprites.

    private Vector2 ViperPos;  // Position of foreground sprite on screen
    public int ScrollHeight; // Height of background sprite
    private Viewport viewport;
    Texture2D ShipTexture;
    Texture2D StarTexture;
    protected override void LoadContent()
        // Create a new SpriteBatch, which can be used to draw textures.
        spriteBatch = new SpriteBatch(GraphicsDevice);
        StarTexture = Content.Load<Texture2D>("starfield");
        ShipTexture = Content.Load<Texture2D>("ship");
        viewport = graphics.GraphicsDevice.Viewport;
        ViperPos.X = viewport.Width / 2;
        ViperPos.Y = viewport.Height - 100;
        ScrollHeight = StarTexture.Height;
  3. In Draw, call Begin for the SpriteBatch representing the background. Specify SpriteBlendMode.None; this will tell the SpriteBatch to ignore alpha color values when drawing sprites. By default the z-order of sprites is the order in which they are drawn.
  4. Draw the background sprites, then call End.

  5. Call Begin for the SpriteBatch representing the foreground. Specify SpriteBlendMode.AlphaBlend; this will cause pixels on the sprite with an alpha value less than 255 to become transparent based on the magnitude of the alpha value. An alpha of 0 will make the pixel completely transparent. Calling Begin with no parameters causes SpriteBatch to default to SpriteBlendMode.AlphaBlend.
  6. Draw the foreground sprites, then call End.


Community Additions