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.