Matt McManis
Matt McManis

Reputation: 4675

WPF 3-Point Gradient

Using C# how can I generate a gradient with 3 points:

The way I'm doing it now is overlaying 2 gradients.

I'd like to simplify it into 1 gradient if possible.

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>

rectangle 1
Gradient White, Blue

rectangle 2
Gradient Black

rectangle 1 + 2
Gradient White, Blue, Black

Upvotes: 0

Views: 2640

Answers (2)

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

Upvotes: 1

Fredrik
Fredrik

Reputation: 2317

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>

enter image description here

Upvotes: 1

Related Questions