2017-02-13 172 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代表索引。