Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xamarin - Gradient background

I'm trying to programmatically set a background gradient like this in Xamarin iOS:

CGColor[] colors = new CGColor[] { new UIColor(red: 0.05f, green:0.44f, blue:0.73f, alpha:1.0f).CGColor,
                new UIColor(red: 45/255, green: 128 / 255, blue: 153 / 255, alpha: 0.01f ).CGColor};
            CAGradientLayer gradientLayer = new CAGradientLayer();
            gradientLayer.Frame = this.View.Bounds;
            gradientLayer.Colors = colors;
            this.View.Layer.AddSublayer(gradientLayer);

And it works, but I have form elements on the screen (labels, buttons, etc) and this is causing all of them to appear faded, as if the layer appears directly on top of the elements. I think this is what the code is doing - it's rendering the entire page, and then adding the layer with opacity on top of the screen (I want it behind it instead).

What I'd like, instead, is to have the background set as gradient, but any elements I add will not be faded and try to match the background colors.

I tried adding a view on top of the standard view, and setting the alpha to 1, background to white, but that didn't seem to help (suggesting my theory that programmatically it's adding a layer on top of everything after it's rendered).

What am I doing wrong? Thanks!

like image 209
NullHypothesis Avatar asked Feb 13 '17 17:02

NullHypothesis


2 Answers

I know I am late for the show but for future reference, I use:

this.View.Layer.InsertSublayer(gradientLayer, 0);

The 0 represents index.

like image 154
GivenMojapelo Avatar answered Sep 19 '22 18:09

GivenMojapelo


Your gradient layer that is assign to the root View of the ViewController is being displayed "behind" all the other Views.

By default, views (UILabel, UIButton, etc) do not have a background color set and thus will blend with that background layer, if that is not the effect that you are looking for assign a background to them:

enter image description here

var button = new UIButton(UIButtonType.System);
button.Frame = new CGRect(40, 300, 120, 40);
button.SetTitle("No Background", UIControlState.Normal);
button.TintColor = UIColor.Red;
View.AddSubview(button);

var button2 = new UIButton(UIButtonType.System);
button2.Frame = new CGRect(180, 300, 100, 40);
button2.SetTitle("Background", UIControlState.Normal);
button2.TintColor = UIColor.Red;
button2.BackgroundColor = UIColor.White;
View.AddSubview(button2);
like image 22
SushiHangover Avatar answered Sep 21 '22 18:09

SushiHangover