How to Create a Gradient in Xamarin Forms

By now you’ve probably found out that Xamarin Forms does not have any built in features for gradients. In order to achieve this you will need to create a custom render, which isn’t too bad. While searching through multiple blog posts it’s pretty easy to find a solution for iOS. But for some reason every Android example only shows how to use a gradient by hard coding the color values in a xml file, and that’s lame. So today I’m going to share a custom render I created for my project that will hopefully be useful for you.

Defining the Render

In the shared platform create the gradient render, which will be a Xamarin Forms View.

This render takes in an array of Colors, this way you can supply as many colors as needed for your gradient. You can also set RoundCorners to true if you want the view to have rounded edges; there is also a CornerRadius property that lets you set the roundness, if needed. The LeftToRight property will set the gradient’s direction to start from left to right. If this property is set to false, then the gradient’s direction will be from top to bottom.

iOS Implementation

The important part here is to convert the array of Xamarin Forms Colors into an array of CGColors, which is required for the CAGradientLayout object.

Android Implementation

The bulk of the cold lives in the method CreateGradient. We have to convert the array of Xamarin Forms Colors into an array of Android Colors. Then we can create the gradient and apply rounded edges if needed. One thing to point out, the Android CornerRadius value will probably need to be higher than the one used on iOS. For example, a corner radius of 20 seems to be the equivalent of a corner radius value of 10 for iOS.

Wrapping Up

All that’s left now is to add the GradientViewRender to our view and initialize it. The XAML is pretty straight forward,

<local:GradientViewRender HorizontalOptions=”Center” WidthRequest=”300″ HeightRequest=”50″ x:Name=”gradientView”></local:GradientViewRender>

Source code can be downloaded here

Leave a Reply