2017-08-30 40 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