Table of Contents

Tinting a Sprite

Demonstrates how to tint a sprite using a Color value.

Overview

Tinting sprites is an easy way to either animate a sprite (when it takes damage) or even to create different characters of different colors. It is quick and efficient to do and all you need is the color to tine with and a single change to your SpriteBatch draw call.

End result

The output of this tutorial

Drawing a Tinted Sprite

  1. Follow the procedures of Drawing a Sprite.

  2. In the Game.Update method, determine the color to tint the sprite.

    In this example, the position of the mouse determines the Red, Green, values to apply to the sprite, the blue is fixed for simplicity.

    // The color tint to apply to the sprite
    protected Color tint;
    
    protected override void Update(GameTime gameTime)
    {
        if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
            Exit();
    
        // TODO: Add your update logic here
        MouseState mouse = Mouse.GetState();
        tint = new Color(mouse.X % 255, mouse.Y % 255, 255);
    
        base.Update(gameTime);
    }
    
  3. In the Game.Draw method, pass the color value created in Game.Update to SpriteBatch.Draw.

    protected override void Draw(GameTime gameTime)
    {
        GraphicsDevice.Clear(Color.CornflowerBlue);
    
        // TODO: Add your drawing code here
        _spriteBatch.Begin();
        // Note the final argument in the Draw call is changed from Color.White to the new "tint" property
        _spriteBatch.Draw(spriteTexture, spritePosition, tint);
        _spriteBatch.End();
    
        base.Draw(gameTime);
    }
    
  4. When all of the sprites have been drawn, call SpriteBatch.End on your SpriteBatch object.

    Moving the mouse around the screen will change the color of the Tint that is applied to the sprite / texture each frame. Alternatively, try switching the input to something else, or for a challenge, animate the tint to make it look like the character is taking damage.

See Also

Concepts

Reference

(Character by upklyak from FreePik)

© 2012 Microsoft Corporation. All rights reserved.