Export (0) Print
Expand All

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 your content as described in the procedures of How To: Draw a Sprite.

    private Vector2 ViperPos;  // Position of foreground sprite on screen
    private 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;
    }
    
  2. In Draw, call Begin for the SpriteBatch.

  3. 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, and then call End.

    spriteBatch.Begin(SpriteBlendMode.None);
    DrawBackground(spriteBatch);
    spriteBatch.End();
    
  5. Call Begin for the SpriteBatch again.

  6. This time, 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.

  7. Draw the foreground sprites, then call End.

    spriteBatch.Begin(SpriteBlendMode.AlphaBlend);
    DrawForeground(spriteBatch);
    spriteBatch.End();
    

Community Additions

ADD
Show:
© 2014 Microsoft