Saturday, April 12, 2008

XAML - Brushes - Gradient Brushes Part 1

There are two gradient brush available in XAML, the RadialGradientBrush and LinearGradientBrush. I am going to show some examples how to use them both.

Firstly, to apply a brush to a visual object in XAML, you need to access the appropriate Brush property. This is likely to be either the Foreground, Background or Fill property.
This first example show how to add a linear gradient to the Fill property of a rectangle.



Code:
<Rectangle Width="100" Height="60">
<Rectangle.Fill>
<LinearGradientBrush>
<GradientStop Offset="1" Color="Red"/>
<GradientStop Offset="0.5" Color="Orange"/>
<GradientStop Offset="0" Color="Yellow"/>
</LinearGradientBrush>
</Rectangle.Fill>
</Rectangle>

Screenshot:


So as you can see from the code, the first thing we need to do is access the Fill property of the Rectangle, which we can do using the tag. Next we define the brush we want to use, in this case we use the tag. So now we are ready to choose the colours and we want to use and where they should be place. This is all done using the tag. Use the Color property to choose your colour and the Offset property to set the position.
By default the far top left of the rectangle is the 0 position and the far right bottom being 1. To set the position to some where within the recangle, you need to use a decial number between these values as done in this example, where the orange colour is set in the middle of the Rectangle at position 0.5 .
It is important to note that you can use values out side of this range, which sets the position to a hyperthetical position outside of the objects visual area. This allows for more options over the colour of the gradient without having to know the value of the colour that you want to display, lets say for instance something between red and orange. This is shown is the example below.



Code:

<Rectangle Width="100" Height="60">
<Rectangle.Fill>
<LinearGradientBrush>
<GradientStop Offset="1.5" Color="Red"/>
<GradientStop Offset="0.5" Color="Orange"/>
<GradientStop Offset="-0.5" Color="Yellow"/>
</LinearGradientBrush>
</Rectangle.Fill>
</Rectangle>

Screenshot



The gradient start and end position can be set to determine the direction of the gradient. This is achieved by setting the StartPoint and EndPoint property of the LinearGradientBrush. Again, like the Offset property, the values run from 0 to 1. Here is a diagram that should help to explain followed by an example.



Code

<Rectangle Width="100" Height="60">
<Rectangle.Fill>
<LinearGradientBrush StartPoint="0.5,0" EndPoint="0.5,1">
<GradientStop Offset="1.5" Color="Red"/>
<GradientStop Offset="0.5" Color="Orange"/>
<GradientStop Offset="-0.5" Color="Yellow"/>
</LinearGradientBrush>
</Rectangle.Fill>
</Rectangle>
Screenshot




As this post is now getting a bit long, I will discuss the RadialGradientBrush in a future post.

No comments: