Telerik blogs

Color Extensions, provided by the .NET MAUI Community Toolkit, give you a way to animate color changes or convert colors in certain situations. Take a look!

Colors are a “language” of communication that allow us to understand an action even before reading any text.

For example, when we see a label in red, we immediately associate it with an error, even before reading what the message actually says. That’s why colors are such an important part of our applications and why we should use them in our favor when building our UIs.

Now, imagine being able to go a step further and play with those colors in different ways, for example, smoothly animating a component from one color to another.

For this and many other useful scenarios, the .NET MAUI Community Toolkit provides us with Color Extensions. In this article, we’ll explore some of my favorites! 💚

What Are Extension Methods? 🤔

As the official documentation defines them:

“Extension methods allow you to add new functionality to existing types without modifying the original type.”

In other words, they allow us to extend the capabilities of existing classes and use those new functionalities in a very natural way throughout our code.

And What Are Color Extensions?

The Color Extensions we’ll explore are available through the .NET MAUI Community Toolkit. In this article, we’ll work with both ColorAnimationExtensions and ColorConversionExtensions.

So, before we get started, make sure to add the corresponding NuGet package:

.NET MAUI Community Toolkit. NuGet Package

And add the following to your code:

âž– For ColorAnimationExtensions:

using CommunityToolkit.Maui.Extensions;

âž– For ColorConversionExtensions:

using CommunityToolkit.Maui.Core.Extensions;

Exploring the ColorAnimationExtensions

These extensions allow us to animate colors in our UI, creating smooth transitions from one color to another.

Background Color

BackgroundColorTo allows you to animate the BackgroundColor of a VisualElement.

It accepts the following parameters:

  • Color: The target color of the animation.
  • Rate: The time interval between each frame of the animation. Its default value is 16 milliseconds. (Optional)
  • Duration: The total duration of the animation. Its default value is 250 milliseconds. (Optional)
  • Easing: Defines how the animation progresses, for example, whether it accelerates or decelerates. Its default value is null. (Optional)

Let’s see an example!

If we want to animate the background color of a button from pink to blue, we can do it as follows:

In your XAML:

<Button 
    x:Name="MyButton" 
    Text="Click here!" 
    TextColor="White" 
    HeightRequest="50" 
    Margin="10,0" 
    BackgroundColor="DeepPink" />

In your C# code:

protected override async void OnAppearing() 
{ 
    base.OnAppearing();
     
    await MyButton.BackgroundColorTo( 
	    Colors.Blue, 
	    rate: 17, 
	    length: 3000, 
	    easing: Easing.Linear 
    ); 
}

Your result should look like the following:

Button smoothly changes color from pink to blue

Text Color

TextColorTo allows you to smoothly transition the text from one color to another through an animation. 📔 You can use the same parameters we previously explored with the BackgroundColorTo extension.

Let’s see an example!

If we want to animate the text color from pink to blue, we can do it as follows:

In your XAML:

<Label 
    x:Name="MyLabel" 
    Text="Hello!" 
    FontSize="50" 
    TextColor="DeepPink" /> 
    </VerticalStackLayout>

In your C# code:

protected override async void OnAppearing() 
{ 
    base.OnAppearing(); 
    
    await MyLabel.TextColorTo( 
	    Colors.Blue, 
	    rate: 16, 
	    length: 3000, 
	    easing: Easing.Linear 
    ); 
}

Your result should look like the following:

Text changes color from pink to blue

Now, Let’s Explore Some ColorAnimationExtensions

ToBlackOrWhite

Imagine you have an app where the background color of a button changes dynamically depending on certain conditions. You don’t know beforehand which background color it will be, and using a fixed text color could make the text difficult to read.

For example, if the button has a black background, you might want to use white text. But if the background changes to yellow, black text would be a better choice.

The ToBlackOrWhite extension helps you handle scenarios like this by converting a color to either black or white, helping you keep the UI of your app readable.

As the official documentation explains:

“This method converts the Color to a monochrome value of Colors.Black or Colors.White.”

Using it is very simple:

<Button 
    x:Name="MyBtn" 
    Text="Hello .NET MAUI!" 
    BackgroundColor="Purple" 
    Clicked="OnButtonClicked"/>

And your C# code:

private void OnButtonClicked(object sender, EventArgs e) 
{ 
    MyBtn.TextColor = 
    MyBtn.BackgroundColor.ToBlackOrWhiteForText(); 
}

IsDark

This extension allows you to determine whether a color is considered dark or not. For example, Black is a dark color, while White is not. It returns a boolean value.

Using IsDark is very simple:

var result = Colors.Black.IsDark();

In this case, the result will be true.

ToInverseColor

The ToInverseColor extension allows you to get the inverse of a color. For example, in this case, the inverse of Black would be White:

var result = Colors.Black.ToInverseColor();

WithRed, WithGreen, WithBlue

This extension allows you to modify only the red component of an existing color, while keeping the other color components unchanged.

For example:

var color = Color.FromRgb(50, 100, 150);

var result = color.WithRed(200);

In this case, the color changes from RGB(50, 100, 150) to RGB(200, 100, 150).

You can also use WithGreen() and WithBlue() to modify the green or blue components of a color.

ToRgbString

This extension allows you to convert a color into a string containing its Red, Green and Blue (RGB) values.

var result = Colors.Red.ToRgbString();

In this case, the result will be: RGB(255,0,0).

Conclusion

And that’s it! These are some of my favorite and most useful Color Extensions from the .NET MAUI Community Toolkit. There are many other interesting ones that I definitely encourage you to explore!

These extensions can help you save code while making it easier to work with colors in your apps. So, give them a try and start incorporating them into your day to day .NET MAUI development! 🚀

Thanks for reading! 💚

References:


LeomarisReyes
About the Author

Leomaris Reyes

Leomaris Reyes is a software engineer from the Dominican Republic specializing in mobile development. She is a 7-time Microsoft MVP and actively builds mobile applications while sharing practical knowledge through technical articles and developer-focused content.

Through her work, she explains programming concepts, developer tools and real-world development practices to help developers grow in their careers.

You can follow her on Instagram and TikTok at @leomarisreyes.dev, read her articles on AskXammy, and connect with her on LinkedIn, where she shares tutorials, insights and resources for developers.

Related Posts

Comments

Comments are disabled in preview mode.