2017-02-13 226 views
2

我试图以编程方式设置在Xamarin的iOS背景梯度是这样的:Xamarin - 渐变背景

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); 

和它的作品,但我在屏幕上的表单元素(标签,按钮等),这导致它们全部变得褪色,好像该图层直接出现在元素的顶部上。我认为这就是代码的作用 - 它渲染整个页面,然后在屏幕上添加不透明的图层(我希望它在它后面)。

我想要的是将背景设置为渐变,但我添加的任何元素都不会褪色并尝试与背景颜色相匹配。

我试着在标准视图的顶部添加一个视图,并将alpha设置为1,将背景设置为白色,但这似乎并没有帮助(暗示我的理论是以编程方式将它添加到一切之后它呈现)。

我在做什么错? 谢谢!

回答

1

指定给ViewController的根View的渐变图层显示在所有其他视图的“后面”。

默认情况下,视图(的UILabel,UIButton的,等)不具有背景色设置,因此将混合与背景层,如果这是不是你正在寻找分配它们的背景效果:

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); 
+0

嗯,所以这似乎并不适合我;您示例中的白色会淡出并与背景颜色相匹配。我甚至将视图的背景设置为红色,但红色与渐变混合。同样对于我的标签,我只想让标签颜色变成白色,而不是褪色。我不想在我的标签上留下背景颜色。有什么想法吗? TY! – NullHypothesis

+0

@NullHypothesis在你的例子中的视图控制器中的'this.View.Layer.AddSublayer'中是'this'吗? – SushiHangover

+0

是的,这是正确的。 – NullHypothesis

2

我知道我迟到了,但节目以供将来参考,我用:

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

0代表索引。