2017-08-30 64 views
0

使用C#我怎樣可以產生3點的梯度:WPF 3點梯度

  • 白色(左)
  • 藍(右)
  • 黑色(底部)

我現在做的方式是疊加2個漸變。

如果可能,我想將它簡化爲1個漸變。

C#

// White to Blue 
LinearGradientBrush WhiteBlue = new LinearGradientBrush(); 
WhiteBlue.StartPoint = new System.Windows.Point(0, 0); 
WhiteBlue.EndPoint = new System.Windows.Point(1, 0); 
WhiteBlue.GradientStops.Add(new GradientStop(Color.FromArgb(255, 255, 255, 255), 0)); // white 
WhiteBlue.GradientStops.Add(new GradientStop(Color.FromArgb(255, 255, 0, 0), 1)); // blue 

rectangle1.Fill = WhiteBlue; 

// Transparent to Black 
LinearGradientBrush Black = new LinearGradientBrush(); 
Black.StartPoint = new System.Windows.Point(0, 0); 
Black.EndPoint = new System.Windows.Point(0, 1); 
Black.GradientStops.Add(new GradientStop(Color.FromArgb(0, 0, 0, 0), 0)); // transparent 
Black.GradientStops.Add(new GradientStop(Color.FromArgb(255, 0, 0, 0), 1)); // black 

rectangle2.Fill = Black; 

XAML

<Rectangle x:Name="rectangle1" 
      HorizontalAlignment="Left" 
      Width="255" 
      Height="255" 
      VerticalAlignment="Top"> 
</Rectangle> 

<Rectangle x:Name="rectangle2" 
      HorizontalAlignment="Left" 
      Width="255" 
      Height="255" 
      VerticalAlignment="Top"> 
</Rectangle> 

矩形1
Gradient White, Blue

矩形2
Gradient Black

矩形1 + 2
Gradient White, Blue, Black

+0

看起來像你的解決方案已經是一個很好的方法:https://stackoverflow.com/questions/2925172/is-there-a-mergedgradientbrush-in-wpf – Fruchtzwerg

+0

另一種方法是從原始像素數據創建一個位圖和在Image控件中顯示它。或者創建一個WritableBitmap並更新它的Buffer。 – Clemens

回答

1

簡而言之,你不能定義二維梯度
最簡單的技術就是您正在使用的技術:使用2個線性漸變執行疊加。
正如Fredrik的回答所暗示的那樣,使用不透明蒙版也同樣有效,但這一切都歸結爲組合漸變:WPF不允許(仍然)定義2D漸變。

1

你可以來相當接近用不透明掩模具有線性漸變畫刷組合,但它不是完美的。

<Rectangle> 
    <Rectangle.Fill> 
     <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0" > 
       <GradientStop Color="Blue" Offset="0"/> 
       <GradientStop Color="Black" Offset="1"/> 
      </LinearGradientBrush> 
     </Rectangle.Fill> 

     <Rectangle.OpacityMask> 
      <LinearGradientBrush StartPoint="0,0" EndPoint="1,1"> 
       <GradientStop Color="Transparent" Offset="0"/> 
       <GradientStop Color="Black" Offset="0.5"/> 
      </LinearGradientBrush> 
     </Rectangle.OpacityMask> 
</Rectangle> 

enter image description here