(616) 371-1037

[email protected]

Gradient Label Control in Xamarin.Forms

April 2, 2019 - Valeriy Kovalenko

1 Comment

As Xamarin.Forms developers we often face cases when controls are not customizable enough to meet our requirements. Luckily for us, the Xamarin team has foreseen these needs and offered a way of how the rendering process can be overridden to customize the appearance and behavior of Xamarin.Forms controls on each platform. Here I am going to show how to use custom renderers to create a gradient label control.

Library Project

Let’s start with creating a class that inherits from the Label control. We have two bindable properties in here: TextColor1 and TextColor2. Our GradientLabel will be filled with a linear gradient using these colors as endpoints.

 

iOS Renderer

All renders are platform specific and therefore are located in platform-specific projects. By using the ExportRenderer attribute, we are telling XF to use the GradientLabelRenderer to render the GradientLabel control. We inherit our renderer from the LabelRenderer because we just want to extend the standard label. When the control is drawn, we create a gradient image and set it as the TextColor using the UIColor.FromPatternImage method. Notice that we also override theOnElementPropertyChanged method. Since we have the bindable properties in the library project, this method will be automagically invoked when TextColor1 or TextColor2 are changed.

Android Renderer

Here is a similar renderer for the Android project. A LinearGradient is used as a shader. We also call Control.Invalidate() to make sure that the control is redrawn when a color is changed.

That’s all we need! Here is how to use the control in XAML:

Some Fun

And now let’s have some fun, just because we can. Everyone loves animations, right? Let’s animate the gradient colors! There is an awesome article on how to create a custom animation in XF: https://blog.xamarin.com/building-custom-animations-in-xamarin-forms/. Let’s reuse their extension class:

Again, since we’re having the bindable properties, everything works without any additional code!

Look at this beauty:

Don’t you want to wrap it into the marquee html tag and send it back to the ’90s? Just kidding, have fun!

Source code is available on GitHub.

Valeriy Kovalenko

One thought on “Gradient Label Control in Xamarin.Forms

  • Geral

    June 11, 2019 at 7:08 pm

    Hi men,
    this controls is very nice, but when is use with formatted string and change dynamically, the gradient dissapear, any solution?

    Reply

Leave a comment

Your email address will not be published. Required fields are marked *