How To: Draw a Masked Sprite over a Background

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 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.

Drawing a Foreground and Background Sprite

To draw a foreground and background sprite

  1. Create the game class, and load resources as described in the procedures 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.

  4. 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.

  5. Draw the background sprites, and then call End.

  6. Call Begin for the SpriteBatch representing the foreground.

  7. Specify SpriteBlendMode.AlphaBlend.

    This will cause pixels on the sprite with an alpha value less than 255 to become progressively 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.

  8. Draw the foreground sprites, then call End.


Community Additions