Xamarin Forms – Creating a Gradient Header

Photo by Luke Chesser on Unsplash

Xamarin Forms – Creating a Gradient Header

Pieter van der Westhuizen's photo
Pieter van der Westhuizen
·Apr 22, 2019·

2 min read

Play this article

In the design document for the Doctriod app you would’ve noticed that it uses a gradient header. To achieve a similar effect (shown in the screenshots below) in Xamarin Forms, we need to make changes in the Shared, Android and iOS project.

image.png

image.png

Shared Project

Start by creating a custom NavigationPage class in the shared project (Doctriod) called GradientHeaderNavigationPage. The class should inherit from the NavigationPage class.

The only thing happening in the class mentioned above is that we’re setting the navigation bar text color to white. Next, because the project uses Prism, we need to change the
RegisterTypes method in the App class (App.xaml.cs) to use our newly created GradientHeaderNavigationPage class instead of the normal Navigationpage.

Android Project

In your Android project(Doctriod.Android) create a new class called GradientHeaderNavigationPageRenderer in the Renderers folder. The class inherits from NavigationPageRenderer and there’s a lot of stuff happening this class, but the method that does the work is called SetGradientBackground which in turn is called from OnViewAdded

You can view the GradientHeaderNavigationPageRenderer.cs file in its entirety on Github

iOS Project

Our last step will be to create a new class called GradientHeaderPageRenderer in our iOS project(Doctriod.iOS) You can create the file anywhere inside the iOS project, but I like to create renderers inside the Renderers folder.

The GradientHeaderPageRenderer will inherit from PageRenderer and the method that does most of the work is called SetGradientBackground and is called from ViewWillAppear

You can view the contents of the entire file on Github.

That should do it. If all goes well you should see similar results as shown in the images at the top of this post. Additional reading and research I used to compile this post is listed below.

Thank you for reading. Until next time, keep coding!

Additional Reading

 
Share this