How to set gradient text fill in WPF
In WPF, you can use gradient text fills to create color gradient effects on text. Below are two methods for setting gradient text fills using XAML and code.
- Set gradient text fill using XAML.
<TextBlock Text="Hello World!">
<TextBlock.Foreground>
<LinearGradientBrush StartPoint="0,0" EndPoint="1,1">
<GradientStop Color="Red" Offset="0" />
<GradientStop Color="Blue" Offset="1" />
</LinearGradientBrush>
</TextBlock.Foreground>
</TextBlock>
In the above code, a LinearGradientBrush is used as the foreground for the text, with two color gradients set as GradientStops. The StartPoint and EndPoint define the starting and ending points of the gradient.
- Set gradient text fill using code.
TextBlock textBlock = new TextBlock();
textBlock.Text = "Hello World!";
LinearGradientBrush gradientBrush = new LinearGradientBrush();
gradientBrush.StartPoint = new Point(0, 0);
gradientBrush.EndPoint = new Point(1, 1);
gradientBrush.GradientStops.Add(new GradientStop(Colors.Red, 0));
gradientBrush.GradientStops.Add(new GradientStop(Colors.Blue, 1));
textBlock.Foreground = gradientBrush;
In the above code, a TextBlock object is created and its text content is set. Then a LinearGradientBrush object is created and its start point, end point, and GradientStop for color gradient are set. Finally, the LinearGradientBrush is set as the foreground for the text.
The effect of gradient text fill in WPF can be achieved using either XAML or code method.