Screen Brightness

From TRCCompSci - AQA Computer Science
Revision as of 13:32, 24 May 2024 by Admin (talk | contribs) (Created page with "MonoGame doesn't contain a built in method to set the brightness of the screen. However this can be created by drawing a black rectangle over the top of the screen and adjust...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

MonoGame doesn't contain a built in method to set the brightness of the screen. However this can be created by drawing a black rectangle over the top of the screen and adjust the transparency of the rectangle to change the brightness.

Variables Required

You will need to create a 1 by 1 pixel texture as seen in some of the other sections. You will also need a value for the brightness level:

// 1 by 1 texture for pixel
Texture2D pixel;

// A value for the player to control brightness.
float brightnessValue = 0f;

LoadContent

Now in the LoadContent method you need to create a texture and give the brightness a value:

// Create a 1x1 Texture.
pixel = new Texture2D(GraphicsDevice, 1, 1);

// Set the color data to the 1x1 Texture.
pixel.SetData<Color>(new Color [] { Color.White });

// Set a default brightnessValue of 0f (full brightness).
brightnessValue = 0f;

Draw Method

Now in the Draw method of your game, make sure the last thing to be drawn is:

spriteBatch.Draw(pixel, new Rectangle(0, 0, graphics.PreferredBackBufferWidth, graphics.PreferredBackBufferHeight), Color.Black * brightnessValue);

Logic to change brightnessValue

You can then use a couple of methods to increase and decrease the brightness:

void IncreaseBrightness()
{
    // Brightness can only be increased if it is under 1f
    if (brightnessValue < 1f )
    {
        brightnessValue+= .05f;
        System.Console.WriteLine("Brightness: {0} %", brightnessValue);
    }
}

void DecreaseBrightness()
{
    // Brightness can only be decreased if it is above 0.
    if (brightnessValue > 0f)
    {
        brightnessValue-= .05f;
        System.Console.WriteLine("Brightness: {0} %", brightnessValue);
    }
}