Gradient Label Control in Xamarin.Forms

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.

public class GradientLabel : Label
{
    public static readonly BindableProperty TextColor1Property = BindableProperty.Create(
        propertyName: nameof(TextColor1),
        returnType: typeof(Color),
        declaringType: typeof(Color),
        defaultValue: Color.Red);
    public Color TextColor1
    {
        get => (Color)GetValue(TextColor1Property);
        set => SetValue(TextColor1Property, value);
    }
    public static readonly BindableProperty TextColor2Property = BindableProperty.Create(
        propertyName: nameof(TextColor2),
        returnType: typeof(Color),
        declaringType: typeof(Color),
        defaultValue: Color.Green);
    public Color TextColor2
    {
        get => (Color)GetValue(TextColor2Property);
        set => SetValue(TextColor2Property, value);
    }
}

 

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.

[assembly: ExportRenderer(typeof(GradientLabel), typeof(GradientLabelRenderer))]
namespace GradientLabelDemo.iOS.Renderers
{
    public class GradientLabelRenderer : LabelRenderer
    {
        public override void Draw(CGRect rect)
        {
            base.Draw(rect);
            if (Control != null)
            {
                SetTextColor();
            }
        }
        protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            base.OnElementPropertyChanged(sender, e);
            SetTextColor();
        }
        private void SetTextColor()
        {
            var image = GetGradientImage(Control.Frame.Size);
            if (image != null)
            {
                Control.TextColor = UIColor.FromPatternImage(image);
            }
        }
        private UIImage GetGradientImage(CGSize size)
        {
            var c1 = (Element as GradientLabel).TextColor1.ToCGColor();
            var c2 = (Element as GradientLabel).TextColor2.ToCGColor();
            UIGraphics.BeginImageContextWithOptions(size, false, 0);
            var context = UIGraphics.GetCurrentContext();
            if (context == null)
            {
                return null;
            }
            context.SetFillColor(UIColor.Blue.CGColor);
            context.FillRect(new RectangleF(new PointF(0, 0), new SizeF((float)size.Width, (float)size.Height)));
            var left = new CGPoint(0, 0);
            var right = new CGPoint(size.Width, 0);
            var colorspace = CGColorSpace.CreateDeviceRGB();
            var gradient = new CGGradient(colorspace, new CGColor[] { c1, c2 }, new nfloat[] { 0f, 1f });
            context.DrawLinearGradient(gradient, left, right, CGGradientDrawingOptions.DrawsAfterEndLocation);
            var img = UIGraphics.GetImageFromCurrentImageContext();
            UIGraphics.EndImageContext();
            return img;
        }
    }
}

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.

[assembly: ExportRenderer(typeof(GradientLabel), typeof(GradientLabelRenderer))]
namespace GradientLabelDemo.Droid.Renderers
{
    public class GradientLabelRenderer : LabelRenderer
    {
        public GradientLabelRenderer(Context context): base(context)
        {
        }
        protected override void OnElementChanged(ElementChangedEventArgs<Label> e)
        {
            base.OnElementChanged(e);
            SetColors();
        }
        protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            base.OnElementPropertyChanged(sender, e);
            SetColors();
        }
        private void SetColors()
        {
            var c1 = (Element as GradientLabel).TextColor1.ToAndroid();
            var c2 = (Element as GradientLabel).TextColor2.ToAndroid();
            Shader myShader = new LinearGradient(
                0, 0, Control.MeasuredWidth, 0,
                c1, c2,
                Shader.TileMode.Clamp);
            Control.Paint.SetShader(myShader);
            Control.Invalidate();
        }
    }
}

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

... xmlns:controls="clr-namespace:GradientLabelDemo.Controls" ...
<controls:GradientLabel
    x:Name="label"
    FontSize="50"
    TextColor1="Yellow"
    TextColor2="Fuchsia"
    Text="Welcome to Xamarin.Forms!"
    HorizontalOptions="Center"
    VerticalOptions="CenterAndExpand" />

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:

async void Handle_Clicked(object sender, System.EventArgs e)
{
    for (int i = 0; i < 50; i++)
    {
        await Task.WhenAll(
        label.ColorTo("a1", label.TextColor1, GetRandomColor(), c => label.TextColor1 = c, 200),
        label.ColorTo("a2", label.TextColor2, GetRandomColor(), c => label.TextColor2 = c, 200));
    }
}
Color GetRandomColor()
{
    return Color.FromRgb(randonGen.Next(255), randonGen.Next(255), randonGen.Next(255));
}

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.

Related Blog Posts

We hope you’ve found this to be helpful and are walking away with some new, useful insights. If you want to learn more, here are a couple of related articles that others also usually find to be interesting:

Our Gear Is Packed and We're Excited to Explore With You

Ready to come with us? 

Together, we can map your company’s software journey and start down the right trails. If you’re set to take the first step, simply fill out our contact form. We’ll be in touch quickly – and you’ll have a partner who is ready to help your company take the next step on its software journey. 

We can’t wait to hear from you! 

Main Contact

This field is for validation purposes and should be left unchanged.

Together, we can map your company’s tech journey and start down the trails. If you’re set to take the first step, simply fill out the form below. We’ll be in touch – and you’ll have a partner who cares about you and your company. 

We can’t wait to hear from you! 

Montage Portal

Montage Furniture Services provides furniture protection plans and claims processing services to a wide selection of furniture retailers and consumers.

Project Background

Montage was looking to build a new web portal for both Retailers and Consumers, which would integrate with Dynamics CRM and other legacy systems. The portal needed to be multi tenant and support branding and configuration for different Retailers. Trailhead architected the new Montage Platform, including the Portal and all of it’s back end integrations, did the UI/UX and then delivered the new system, along with enhancements to DevOps and processes.

Logistics

We’ve logged countless miles exploring the tech world. In doing so, we gained the experience that enables us to deliver your unique software and systems architecture needs. Our team of seasoned tech vets can provide you with:

Custom App and Software Development

We collaborate with you throughout the entire process because your customized tech should fit your needs, not just those of other clients.

Cloud and Mobile Applications

The modern world demands versatile technology, and this is exactly what your mobile and cloud-based apps will give you.

User Experience and Interface (UX/UI) Design

We want your end users to have optimal experiences with tech that is highly intuitive and responsive.

DevOps

This combination of Agile software development and IT operations provides you with high-quality software at reduced cost, time, and risk.

Trailhead stepped into a challenging project – building our new web architecture and redeveloping our portals at the same time the business was migrating from a legacy system to our new CRM solution. They were able to not only significantly improve our web development architecture but our development and deployment processes as well as the functionality and performance of our portals. The feedback from customers has been overwhelmingly positive. Trailhead has proven themselves to be a valuable partner.

– BOB DOERKSEN, Vice President of Technology Services
at Montage Furniture Services

Technologies Used

When you hit the trails, it is essential to bring appropriate gear. The same holds true for your digital technology needs. That’s why Trailhead builds custom solutions on trusted platforms like .NET, Angular, React, and Xamarin.

Expertise

We partner with businesses who need intuitive custom software, responsive mobile applications, and advanced cloud technologies. And our extensive experience in the tech field allows us to help you map out the right path for all your digital technology needs.

  • Project Management
  • Architecture
  • Web App Development
  • Cloud Development
  • DevOps
  • Process Improvements
  • Legacy System Integration
  • UI Design
  • Manual QA
  • Back end/API/Database development

We partner with businesses who need intuitive custom software, responsive mobile applications, and advanced cloud technologies. And our extensive experience in the tech field allows us to help you map out the right path for all your digital technology needs.

Our Gear Is Packed and We're Excited to Explore with You

Ready to come with us? 

Together, we can map your company’s tech journey and start down the trails. If you’re set to take the first step, simply fill out the contact form. We’ll be in touch – and you’ll have a partner who cares about you and your company. 

We can’t wait to hear from you! 

Thank you for reaching out.

You’ll be getting an email from our team shortly. If you need immediate assistance, please call (616) 371-1037.