MonoGame - Change Brightness
By Stephen Armstrong // March 10, 2020
Control how bright your game is.
MonoGame has no set function for changing the brightness of your game.
However, it is very easy to replicate the effect of various brightness levels by drawing a full-screen black image and then altering its transparency.
Use the following C# code to effectively alter the screen’s brightness in a MonoGame project.
Set Up
Add two fields (a Texture2D and byte) to your Game1:
// A single-pixel texture that will be stretched to cover the screen.
Texture2D pixel;
// A value for the player to control brightness.
byte brightnessValue;
Now go to LoadContent() and set the value of the Texture2D and byte.
// 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 100 (full brightness).
brightnessValue = 100;
The Texture2D and byte are now ready to use.
Applying Brightness
Go to Game1.cs’s Draw() cycle, and add the following code just before you end the SpriteBatch:
// brightnessMultiplier will contain a percentage value of transparency.
float brightnessMultiplier;
// Remove the current brightnessValue from 100 and divide it by 100 to get a value between 0 and 1.00.
brightnessMultiplier = 100 - brightnessValue;
brightnessMultiplier /= 100;
// Stretch the single-pixel texture to cover the screen. The color black is rendered using brightnessMultiplier as its transparency value.
spriteBatch.Draw(pixel, new Rectangle(0, 0, graphics.PreferredBackBufferWidth, graphics.PreferredBackBufferHeight), Color.Black * brightnessMultiplier);
Everything is now set up for the brightness to be used.
Modifying Brightness
Add the following methods to your Game1:
void IncreaseBrightness()
{
// Brightness can only be increased if it is under 100.
if (brightnessValue < 100)
{
brightnessValue++;
System.Console.WriteLine("Brightness: {0} %", brightnessValue);
}
}
void DecreaseBrightness()
{
// Brightness can only be decreased if it is above 0.
if (brightnessValue > 0)
{
brightnessValue--;
System.Console.WriteLine("Brightness: {0} %", brightnessValue);
}
}
Calling these methods will increase and decrease the brightness.
Testing
To test that these methods work, go to Game1.cs’ Update() cycle and add the following code:
// Press/Hold the Page Up key to increase the brightness.
if (Keyboard.GetState().IsKeyDown(Keys.PageUp))
{
IncreaseBrightness();
}
// Press/Hold the Page Down key to increase the brightness.
if (Keyboard.GetState().IsKeyDown(Keys.PageDown))
{
DecreaseBrightness();
}
Run your game and you can use the PageUp and PageDown keys to modify the brightness.
You will also see the percentage of the current screen brightness in the Output.