User Tools

Site Tools


notes:uwp:gradient

Gradient in XAML

Use gradients to set the value of the Background or Fill property of elements. You can change the color as well as transparency in the gradient definition.

A gradient is defined using a vector and a set of gradient stops. Each gradient stop has a position from 0 to 1 (0% to 100%):

Example: Define a simple LinearGradientBrush:

<!-- gradient defined directly in an element-->
<Rectangle Width="300" Height="200">
    <Rectangle.Fill>
        <LinearGradientBrush StartPoint="0.5,0" EndPoint="0.5,1">
            <GradientStop Color="Red" Offset="0" />
            <GradientStop Color="Yellow" Offset="0.4" />
            <GradientStop Color="Green" Offset="0.6" />
            <GradientStop Color="Blue" Offset="1" />
        </LinearGradientBrush>
    </Rectangle.Fill>
</Rectangle>
<!-- gradient defined in resources-->
<Page.Resources>
    <LinearGradientBrush x:Key="GradientBackground" StartPoint="0.5,0" EndPoint="0.5,1">
        <GradientStop Color="Red" Offset="0" />
        <GradientStop Color="Yellow" Offset="0.4" />
        <GradientStop Color="Green" Offset="0.6" />
        <GradientStop Color="Blue" Offset="1" />
    </LinearGradientBrush>
</Page.Resources>
 
<Grid>
    <Rectangle Width="300" Height="200" Fill="{StaticResource GradientBackground}" />
</Grid>

Example: Create gradient stops programmatically:

<Rectangle Loaded="Rectangle_Loaded">
    <Rectangle.Fill>
        <LinearGradientBrush StartPoint="0,0" EndPoint="1,0" />
    </Rectangle.Fill>
</Rectangle>
using Windows.UI;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Shapes;
 
namespace TestApp
{
    public sealed partial class MainPage : Page
    {
        public MainPage()
        {
            this.InitializeComponent();
        }
 
        private void Rectangle_Loaded(object sender, RoutedEventArgs args)
        {
            var rect = sender as Rectangle;
            var brush = rect.Fill as LinearGradientBrush;
 
            brush.GradientStops.Clear();
 
            var s1 = new GradientStop();
            s1.Color = Colors.Blue;
            s1.Offset = 0.0;
            brush.GradientStops.Add(s1);
 
            var s2 = new GradientStop();
            s2.Color = Colors.Red;
            s2.Offset = 1.0;
            brush.GradientStops.Add(s2);
        }
    }
}
notes/uwp/gradient.txt · Last modified: 2017/01/13 by admin