Horizontal And Vertical Gradient Color In Xamarin.Forms

Introduction

Sometimes, we may get the requirement to set Gradient Color for Layout or page. In this article, we can learn how we can set a Gradient Color for Layout or Page using CustomRenderer in Xamarin.Forms.

Requirements

  • This article's source code is prepared by using Visual Studio. And it is better to install the latest Visual Studio updates from here.
  • This article is prepared on a MAC machine.
  • This sample project is Xamarin.Forms PCL project.
  • This sample app is targeted for Android, iOS. And tested for Android & iOS.

Description

The creation of a Xamarin.Forms project is very simple in Visual Studio for Mac. It will create three projects:

  1. Shared Code
  2. Xamarin.Android
  3. Xamarin.iOS

The Mac system with Visual Studio for Mac doesn't support Windows projects (UWP, Windows, Windows Phone).

The following steps will show you how to create Xamarin.Forms projects in a Mac system with Visual Studio.

First, open Visual Studio for Mac. And click on New Project.

Xamarin

After that, we need to select whether you're doing Xamarin.Forms or Xamarin.Android or Xamarin.iOS project. If we want to create Xamarin.Forms project just follow the below screenshot.

Xamarin

Then, we have to give the app name; i.e., GradientColorDemo.

Xamarin

Note:

In the above screen under Shared Code, select Portable class Library or Use Shared Library.

Then, click on Next Button and the following screenshot will be displayed. In that screen, we have to browse the file path where we want to save that application on our PC.

Xamarin

After clicking on the create button it will create the RoundedCornerViewDemo Xamarin.Forms project like below.

Xamarin

And the project structure will be,

  • GradientColorDemo: It is for Shared Code
  • Droid: It is for Android.
  • iOS: It is for iOS 
 Xamarin

We need to follow the below steps to set Gradient Color for StackLayout.

Portable Class Library (PCL)

Step 1

In PCL, create a class name GradientColorStack inside the CustomControls folder and which should inherit from StackLayout like below.

GradientColorStack.cs

  1. using Xamarin.Forms;  
  2. namespace GradientColorDemo.CustomControls {  
  3.     public class GradientColorStack: StackLayout {  
  4.         public Color StartColor {  
  5.             get;  
  6.             set;  
  7.         }  
  8.         public Color EndColor {  
  9.             get;  
  10.             set;  
  11.         }  
  12.     }  

Step 2

Create your own Xaml page named GradientColorPage.xaml, and make sure to refer to  "GradientColorStack" class in Xaml by declaring a namespace for its location and using the namespace prefix on the control element. The following code example shows how the "GradientColorStack" renderer class can be consumed by a XAML page:

GradientColorPage.xaml

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <ContentPage xmlns="http://xamarin.com/schemas/2014/forms" 
  3. xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" 
  4. xmlns:local="clr-namespace:GradientColorDemo.CustomControls; assembly:GradientColorDemo" 
  5. x:Class="GradientColorDemo.Views.GradientColorPage">  
  6.     <Grid VerticalOptions="FillAndExpand" RowSpacing="0">  
  7.         <Grid.RowDefinitions>  
  8.             <RowDefinition Height="*" />  
  9.             <RowDefinition Height="*" /> </Grid.RowDefinitions>  
  10.         <Grid Grid.Row="0" BackgroundColor="#3e5151">  
  11.             <StackLayout VerticalOptions="Center">  
  12.                 <Label Text="Normal color for StackLayout" HorizontalTextAlignment="Center" VerticalTextAlignment="Center" TextColor="White" /> </StackLayout>  
  13.         </Grid>  
  14.         <Grid Grid.Row="1">  
  15.             <local:GradientColorStack StartColor="#3e5151" EndColor="#decba4">  
  16.                 <StackLayout VerticalOptions="CenterAndExpand">  
  17.                     <Label Text="Horizontal Gradient color for StackLayout" HorizontalTextAlignment="Center" VerticalTextAlignment="Center" TextColor="White" /> 
  18.                 </StackLayout>  
  19.             </local:GradientColorStack>  
  20.         </Grid>  
  21.     </Grid>  
  22. </ContentPage>  

Note
The "local" namespace prefix can be named anything. However, the clr-namespace and assembly values must match the details of the custom renderer class. Once the namespace is declared the prefix is used to reference the custom control.

GradientColorPage.xaml.cs

  1. using Xamarin.Forms;  
  2. namespace GradientColorDemo.Views {  
  3.     public partial class GradientColorPage: ContentPage {  
  4.         public GradientColorPage() {  
  5.             InitializeComponent();  
  6.         }  
  7.     }  
  8. }  

Xamarin.Android

In Android project, create a class with GradientColorStackRenderer name inside the CustomControls folder:

GradientColorStackRenderer.cs

  1. using System;  
  2. using GradientColorDemo.Droid;  
  3. using GradientColorDemo.CustomControls;  
  4. using Xamarin.Forms;  
  5. using Xamarin.Forms.Platform.Android;  
  6. [assembly: ExportRenderer(typeof(GradientColorStack), typeof(GradientColorStackRenderer))]  
  7. namespaceDroid {  
  8.     public class GradientColorStackRenderer: VisualElementRenderer < StackLayout > {  
  9.         private Color StartColor {  
  10.             get;  
  11.             set;  
  12.         }  
  13.         private Color EndColor {  
  14.             get;  
  15.             set;  
  16.         }  
  17.         protected override void DispatchDraw(global::Android.Graphics.Canvas canvas)   
  18.         {  
  19.             #region for Vertical Gradient  
  20.             //var gradient = new Android.Graphics.LinearGradient(0, 0, 0, Height,      
  21.             # endregion
  22.             # region  for Horizontal Gradient  
  23.             var gradient = newGraphics.LinearGradient(0, 0, Width, 0,   
  24.             #endregion 
  25.             this.StartColor.ToAndroid(), 
  26.             this.EndColor.ToAndroid(), 
  27.             Android.Graphics.Shader.TileMode.Mirror);  
  28.             var paint = new Android.Graphics.Paint() {  
  29.                 Dither = true,  
  30.             };  
  31.             paint.SetShader(gradient);  
  32.             canvas.DrawPaint(paint);  
  33.             base.DispatchDraw(canvas);  
  34.         }  
  35.         protected override void OnElementChanged(ElementChangedEventArgs<StackLayout> e) {  
  36.             base.OnElementChanged(e);  
  37.             if (e.OldElement != null || Element == null) {  
  38.                 return;  
  39.             }  
  40.             try {  
  41.                 var stack = e.NewElement as GradientColorStack;  
  42.                 this.StartColor = stack.StartColor;  
  43.                 this.EndColor = stack.EndColor;  
  44.             } catch (Exception ex) {  
  45.                 Syatem.Diagnostics.Debug.WriteLine(@ "ERROR:", ex.Message);  
  46.             }  
  47.         }  
  48.     }  
  49. }  

Here OnElementChanged method instantiates an Android UI Layout and in that, I mentioned vertical and horizontal gradients within #region.

Output: 

       Xamarin

Xamarin.iOS

In iOS project, create a class with GradientColorStackRenderer name inside the CustomControls folder,

GradientColorStackRenderer.cs

  1. using CoreAnimation;  
  2. using CoreGraphics;  
  3. using GadientColorDemo.CustomControls;  
  4. using GadientColorDemo.iOS;  
  5. using Xamarin.Forms;  
  6. using Xamarin.Forms.Platform.iOS;  
  7. [assembly: ExportRenderer(typeof(GradientColorStack), typeof(GradientColorStackRenderer))]  
  8. namespace GadientColorDemo.iOS {  
  9.     public class GradientColorStackRenderer: VisualElementRenderer <StackLayout> {  
  10.         public override void Draw(CGRect rect) {  
  11.             base.Draw(rect);  
  12.             GradientColorStack stack = (GradientColorStack)this.Element;  
  13.             CGColor startColor = stack.StartColor.ToCGColor();  
  14.             CGColor endColor = stack.EndColor.ToCGColor();  
  15.             #region for Vertical Gradient  
  16.             //var gradientLayer = new CAGradientLayer();     
  17.             # endregion
  18.             # region for Horizontal Gradient  
  19.             var gradientLayer = new CAGradientLayer() {  
  20.                 StartPoint = new CGPoint(0, 0.5),  
  21.                 EndPoint = new CGPoint(1, 0.5)  
  22.             };  
  23.             #endregion  
  24.             gradientLayer.Frame = rect;  
  25.             gradientLayer.Colors = new CGColor[] {  
  26.                 startColor,  
  27.                 endColor  
  28.             };  
  29.             NativeView.Layer.InsertSublayer(gradientLayer, 0);  
  30.         }  
  31.     }  
  32. }  

Here OnElementChanged method instantiates an iOS UI and in that, I mentioned vertical and horizontal gradients within #region.

Output

Xamarin

Please download sample from here.

X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now