C#
.NET
MAUI
Android
iOS
Changing the screen brightness in .NET MAUI
Learn how to change the screen brightness in your MAUI Android and iOS apps.
Intro
We'll define a function that takes a float argument which controls how bright the screen is. This value ranges from 0 for the lowest brightness up to 1 for the highest brightness. We'll also return the previous brightness so we know what to reset it to.
Create the cross platform api
Partial implementations must all share the same class name and namespace
Create a new file called BrightnessService.cs that defines our api
C#namespace MyProject.Services
{
public partial class BrightnessService
{
public partial float SetBrightness(float brightness);
}
}
Android implementation
Inside your Platforms > Android folder, create a new file called BrightnessService.cs
C#using Android.Views;
namespace MyProject.Services
{
public partial class BrightnessService
{
public partial float SetBrightness(float brightness)
{
try
{
var window = Microsoft.Maui.ApplicationModel.Platform.CurrentActivity.Window;
var attributesWindow = new WindowManagerLayoutParams();
var previousBrightness = window.Attributes.ScreenBrightness;
attributesWindow.CopyFrom(window.Attributes);
attributesWindow.ScreenBrightness = brightness;
window.Attributes = attributesWindow;
return previousBrightness;
}
catch
{
return 0;
}
}
}
}
iOS implementation
Inside your Platforms > iOS folder, create a new file called BrightnessService.cs
C#using UIKit;
namespace MyProject.Services
{
public partial class BrightnessService
{
public partial float SetBrightness(float brightness)
{
try
{
var previousBrightness = UIScreen.MainScreen.Brightness;
UIScreen.MainScreen.Brightness = brightness;
return (float)previousBrightness;
}
catch
{
return 0;
}
}
}
}
Usage
C#var brightnessService = new BrightnessService();
var previousBrightness = brightnessService.SetBrightness(1); // Max brightness
// (Optional) Later on reset the brightness to what it was
brightnessService.SetBrightness(previousBrightness);