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 to Make a Gradient Background Like Android in iOS

JohnBeansJohnBeans USMember ✭✭
edited July 2014 in Xamarin.Forms

If you like:
1. Matching your iOS ContentPages to the default dark background gradient of Android
2. Dark background gradients in general
3. Applying your own background effects

Here's a template for you.

Create a new file in your iOS project. Name it whatever you want (such as MyContentPageRenderer.cs).

In this particular example, we're creating a gradient layer and adding it as a sublayer to all ContentPages. Any ContentPage that has BackgroundColor = Color.Transparent will "show" the background gradient. But if you set the page's BackgroundColor to a solid color, it will block the gradient. Ditto for any objects on your page.

using System;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;
using MonoTouch.UIKit;
using MonoTouch.CoreGraphics;
using MonoTouch.CoreAnimation;
using MonoTouch.Foundation;

[assembly: ExportRenderer(typeof(ContentPage), typeof(MyContentPageRenderer))]

    public class MyContentPageRenderer: PageRenderer
        public CAGradientLayer gradient;
        public MyContentPageRenderer ():base()
        protected override void ViewDidLoad ()
            base.ViewDidLoad ();
            gradient = new CAGradientLayer ();
            gradient.Frame = View.Bounds;
            gradient.NeedsDisplayOnBoundsChange = true;
            gradient.MasksToBounds = true;
            gradient.Colors = new CGColor[]{ UIColor.Black.CGColor, UIColor.DarkGray.CGColor };
            View.Layer.InsertSublayer (gradient, 0);

        public override void ViewWillLayoutSubviews ()
            base.ViewWillLayoutSubviews ();
            gradient.Frame = View.Bounds;

The ViewWillLayoutSubviews() routine handles resizing when the device rotates.


  • adamkempadamkemp USInsider, Developer Group Leader mod

    I don't think you should do the creation of the layer in OnElementChanged. In theory that method could be called multiple times. Why not do it in ViewDidLoad?

  • JohnBeansJohnBeans USMember ✭✭

    Adam, you're right. Updated.

  • MohnishPandyaMohnishPandya INMember

    Thanks a lot...worked like a charm..

Sign In or Register to comment.