简体   繁体   English

WPF 3点渐变

[英]WPF 3-Point Gradient

Using C# how can I generate a gradient with 3 points: 使用C#如何生成3个点的渐变:

  • White (left) 白色(左)
  • Blue (right) 蓝色(右)
  • Black (bottom) 黑色(底部)

The way I'm doing it now is overlaying 2 gradients. 我现在的操作方式是覆盖2个渐变。

I'd like to simplify it into 1 gradient if possible. 如果可能的话,我想将其简化为1个渐变。

C# 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 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>

rectangle 1 矩形1
渐变白,蓝色

rectangle 2 矩形2
渐变黑

rectangle 1 + 2 矩形1 + 2
渐变白,蓝,黑

You can come quite close with a opacity mask combined with a linear gradient brush, but its not perfect. 您可以使用不透明蒙版与线性渐变画笔相结合,但效果并不理想。

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

在此处输入图片说明

Simply put, you can not define a two-dimensional gradient . 简而言之, 您无法定义二维渐变
The simplest technique is the one you are using: perform an overlay with 2 linear gradients. 最简单的技术是您正在使用的一种技术:使用2个线性渐变执行叠加。
Using an opacity mask, as Fredrik's answer suggests, is equally valid, but it all comes down to combining gradients: WPF does not allow (still) defining a 2D gradient. 正如Fredrik的答案所暗示的那样,使用不透明蒙版同样有效,但是所有这些都归结为组合渐变:WPF不允许(仍然)定义2D渐变。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM