Forum Xamarin.Forms
We are excited to announce that the Xamarin Forums are moving to the new Microsoft Q&A experience. Q&A is the home for technical questions and answers at across all products at Microsoft now including Xamarin!

We encourage you to head over to Microsoft Q&A for .NET for posting new questions and get involved today.

How can I achieve a gredient in the Navigation bar please, for Android, iOS and UWP please?

Cdn_EuroCdn_Euro Member ✭✭✭

Trying to achieve a horizontal gradient in the Navigation bar such as in the photo. How can I do this please for all platforms?

Answers

  • jezhjezh Member, Xamarin Team Xamurai

    You can use custom render to achieve this function.

    In Shared Project:

    public class NavigationPageGradientHeader : NavigationPage
    {
        public NavigationPageGradientHeader(Page root) : base(root)
        {
        }
    
        public static readonly BindableProperty RightColorProperty =
          BindableProperty.Create(propertyName: nameof(RightColor),
              returnType: typeof(Color),
              declaringType: typeof(NavigationPageGradientHeader),
              defaultValue: Color.Accent);
    
        public static readonly BindableProperty LeftColorProperty =
           BindableProperty.Create(propertyName: nameof(LeftColor),
               returnType: typeof(Color),
               declaringType: typeof(NavigationPageGradientHeader),
               defaultValue: Color.Accent);
    
        public Color RightColor
        {
            get { return (Color)GetValue(RightColorProperty); }
            set { SetValue(RightColorProperty, value); }
        }
    
        public Color LeftColor
        {
            get { return (Color)GetValue(LeftColorProperty); }
            set { SetValue(LeftColorProperty, value); }
        }
    }
    

    in Android project:

    [assembly: ExportRenderer(typeof(NavigationPageGradientHeader), typeof(NavigationPageGradientHeaderRenderer))]
    namespace YournameSpace.Droid
    {
        public class NavigationPageGradientHeaderRenderer : NavigationRenderer
        {
            protected override void OnElementChanged(ElementChangedEventArgs<NavigationPage> e)
            {
                base.OnElementChanged(e);
    
                //run once when element is created
                if (e.OldElement != null || Element == null)
                {
                return;
                }
    
                var control = (NavigationPageGradientHeader)this.Element;
                var context = (MainActivity)this.Context;
    
                context.ActionBar.SetBackgroundDrawable(new GradientDrawable(GradientDrawable.Orientation.RightLeft, new int[] { control.RightColor.ToAndroid(), control.LeftColor.ToAndroid() }));
            }
        }
    }
    

    For more details, you can check: https://stackoverflow.com/questions/46809733/how-to-add-a-gradient-in-xamarin-forms-toolbar-and-uinavigationbar

Sign In or Register to comment.