Introduction to Brushes in Silverlight 4.0

This article explains the basics of painting shapes in a Silverlight application using different types of brushes available in Silverlight SDK, with both declarative and code-behind methods. We will mainly look at SolidColorBrush and LinearGradientBrush in this article.

Contributed by
Rating: 5 stars5 stars5 stars5 stars5 stars / 1
June 21, 2010
Rate this Article:
MEH MEH++


SEARCH ASP FREE
TOOLS YOU CAN USE

advertisement

The entire source code for this article is available in the form of a free downloadable zip file. The solution was developed using Microsoft Visual Studio 2010 Ultimate Edition with Microsoft Silverlight 4.0 RC2 on Windows 7 Ultimate edition. I didn't really test it in any other environment. I request that you post in the discussion area if you have any problems in execution.

Getting started with painting shapes in Silverlight

Before we start on brushes, let us start creating a simple Silverlight 4.0 application with two Rectangles. The following are the steps:

  • Open Microsoft Visual Studio 2010.

  • Go to File || New Project.

  • In this "Installed Templates," select "Silverlight" and choose "Silverlight Application" in the right pane.

  • Provide the project name and solution name ("SlBrushes" in my case) and click on OK.

  • Once the "New Silverlight Application" dialog comes up, make sure that the following options are selected, and click on okay.

 

 

  • You should have two projects created: one for Silverlight and the other (.web) for hosting the Silverlight application.

  • Now that you have created the solution successfully, open MainPage.xaml and modify the code as shown below:

<UserControl x:Class="SLBrushes.MainPage"

    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"

    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"

    mc:Ignorable="d"

    d:DesignHeight="300" d:DesignWidth="400">

 

 

    <Canvas x:Name="LayoutRoot" Background="White">

        <Rectangle Canvas.Left="156" Canvas.Top="80" Height="101" Name="Rectangle2" Stroke="Black" StrokeThickness="1" Width="199" Fill="#FFBABAF2" />

 

 

        <Rectangle Canvas.Left="40" Canvas.Top="33" Height="100" Name="Rectangle1" Stroke="Black" StrokeThickness="1" Width="200" />

       

    </Canvas>

</UserControl>

 

Note that you have to replace "SlBrushes" with your own namespace throughout this article.

Once you hit F5, you should see two rectangles as shown below:

the next section will explain the above code in detail.

Understanding Brushes in Silverlight: SolidColorBrush

Any shape (or control) in Silverlight can be painted with a color (or pattern) using brushes. Different brushes exist for different types of painting mechanisms. In this section, we will look at the SolidColorBrush, the simplest of all brushes.

Let us go through the previous example:

    <Canvas x:Name="LayoutRoot" Background="White">

        <Rectangle Canvas.Left="156" Canvas.Top="80" Height="101" Name="Rectangle2" Stroke="Black" StrokeThickness="1" Width="199" Fill="#FFBABAF2" />

 

 

        <Rectangle Canvas.Left="40" Canvas.Top="33" Height="100" Name="Rectangle1" Stroke="Black" StrokeThickness="1" Width="200" />

       

    </Canvas>

Using a "Canvas" layout, I can place Silverlight elements (shapes or controls) at specific x and y co-ordinates (absolute positioning). Even though more powerful layouts exist (than Canvas Layout), I chose the "Canvas" layout just to make this article quite simple to understand. 

I created two "Rectangle" shapes. Rectangle1 will be on top of Rectangle2. By default, Rectangle1 is not filled with any color (transparent). Rectangle2 is painted with the color "#FFBABAF2" (kind of a lavender shade) using the "Fill" attribute. In simple words, Rectangle2 will be painted solidly and completely with the "#FFBABAF2" color (excluding borders).

I did not specify any "SolidColorBrush" in the above sample. However, by default, when we specify a color name (or Hex number representing color) to a "Fill" attribute in design mode (declarative model), it defaults to "SolidColorBrush."

You can also modify the above with the following (to be more specific):

        <Rectangle Canvas.Left="156" Canvas.Top="80" Height="101" Name="Rectangle2" Stroke="Black" StrokeThickness="1" Width="199">

            <Rectangle.Fill>

                <SolidColorBrush Color="#FFBABAF2"/>

            </Rectangle.Fill>

        </Rectangle>

 

Let us see how to achieve the same using a code-behind (dynamically through programming). Modify MainPage.xaml.vb as shown below:

Partial Public Class MainPage

    Inherits UserControl

 

 

    Public Sub New()

        InitializeComponent()

    End Sub

 

 

    Private GetColorFromHex As Func(Of String, Color) =

        Function(HexColor) As Color

            Return Color.FromArgb(

                  Convert.ToByte(HexColor.Substring(1, 2), 16),

                  Convert.ToByte(HexColor.Substring(3, 2), 16),

                  Convert.ToByte(HexColor.Substring(5, 2), 16),

                  Convert.ToByte(HexColor.Substring(7, 2), 16)

          )

        End Function

 

 

 

 

    Private Sub MainPage_Loaded(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Me.Loaded

 

 

        Me.Rectangle1.Fill = New SolidColorBrush(GetColorFromHex("#FF336699"))

 

 

    End Sub

 

 

End Class

The next section explains the above code.

Understanding Brushes in Silverlight: SolidColorBrush continued

Silverlight only accepts the assignment of "Color" objects from code-behind. As of now, "Color" has only the "FromArgb" method to represent a custom color. The "FromArgb" method accepts four values as parameters:

  •  Alpha (transparency) - first two chars of HEX.

  • Red - second two chars of HEX.

  • Green - third two chars of HEX.

  • Blue - fourth two chars of HEX.

The value for each of the above should be in between 0 and 255 (0 being no color applied and 255 being full color applied). When you need no transparency, you can provide 255 as the Alpha value. If you need the color to be half transparent, you can provide 128 as the Alpha value.

If you already have RGB color values, you can directly use the "Color.FromArgb" method. But if you have HEX values representing the same, you can take advantage of the following:

    Private GetColorFromHex As Func(Of String, Color) =

        Function(HexColor) As Color

            Return Color.FromArgb(

                  Convert.ToByte(HexColor.Substring(1, 2), 16),

                  Convert.ToByte(HexColor.Substring(3, 2), 16),

                  Convert.ToByte(HexColor.Substring(5, 2), 16),

                  Convert.ToByte(HexColor.Substring(7, 2), 16)

          )

        End Function

In the above code, "GetColorFromHex" acts as a function (anonymous delegate) which accepts a HEX string and converts the same to a "Color" object. You can also do that using a separate method (if you don't feel comfortable with the above approach). 

The main line to concentrate on is the following:

        Me.Rectangle1.Fill = New SolidColorBrush(GetColorFromHex("#FF336699"))

I am instantiating a "SolidColorBrush" object by passing a color (with no transparency). When the brush is assigned the "Fill" property, the entire Rectangle1 gets filled with solid color specified.

Once you execute the application with the above code, you should have the output shown below:

You can also test the transparency (in this case 50%) by modifying the first two HEX chars to "80" (128 in decimal) as shown below:

        Me.Rectangle1.Fill = New SolidColorBrush(GetColorFromHex("#80336699"))

In this case, you should see the output shown below:

Understanding Brushes in Silverlight: LinearGradientBrush

In previous sections, we saw how to paint a shape with a single solid color. Now, say we would like to have a shape get painted with two colors (at least) blending into each other. In other words, we would like to start painting with a single color and gradually (using different shades of the same color) turn in to another color at the end.

The above can be achieved using either the LinearGradientBrush or the RadialGradientBrush. In this section, we will look at the "LinearGradientBrush."  Let us modify our code as follows:

    <Canvas x:Name="LayoutRoot" Background="White">

 

 

        <Rectangle Canvas.Left="156" Canvas.Top="80" Height="101" Name="Rectangle2" Stroke="Black" StrokeThickness="1" Width="199" Fill="#FFBABAF2" />

 

 

        <Rectangle Canvas.Left="40" Canvas.Top="33" Height="100" Name="Rectangle1" Stroke="Black" StrokeThickness="1" Width="200" >

            <Rectangle.Fill>

                <LinearGradientBrush>

                    <GradientStop Color="Blue" Offset="0"/>

                    <GradientStop Color="Red" Offset="1"/>

                </LinearGradientBrush>

            </Rectangle.Fill>

        </Rectangle>

       

    </Canvas>

 

Executing your application should deliver the following result:

The main lines to concentrate on are the following:

                <LinearGradientBrush>

                    <GradientStop Color="Blue" Offset="0"/>

                    <GradientStop Color="Red" Offset="1"/>

                </LinearGradientBrush>

In the above fragment, you are specifying that the Rectangle must be painted using LinearGradientBrush. A LinearGradientBrush can have multiple colors to be used as part of the gradient color pattern. In this case, we used only two colors for gradient effect, "Blue" and "Red."  By default, the LinearGraidentBrush paints with a diagonal effect (we will customize this later in my upcoming articles).

Each color participating in the gradient effect is determined by "GradientStop" which defines the color and its stopping (not starting) position. The next section explains this in more detail.

Understanding Brushes in Silverlight: LinearGradientBrush continued

To understand the "Offset" property of "GradientStop," let us modify our code to something different:

                 <LinearGradientBrush>

                    <GradientStop Color="Blue" Offset="0.5"/>

                    <GradientStop Color="Red" Offset="1"/>

                </LinearGradientBrush>

The above would give you a result as shown below:

 

From the above, you should conclude that the "Offset" value of any GradientStop should always be in between 0.0 and 1.0 (both inclusive). The beginning of the entire Gradient pattern will always be represented as 0, and the ending will be 1 (regardless of any number of gradient stops in between).

Now, let us work on the code-behind to achieve the same as we did above. Modify the code-behind to look like the following:

    Private Sub MainPage_Loaded(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Me.Loaded

 

 

        'start: with basic gradient (from code-behind)

        Dim brBlueRedGrad = New LinearGradientBrush()

 

 

        Dim GradBlue As New GradientStop()

        GradBlue.Color = ColorHelper.Blue

        GradBlue.Offset = 0

        brBlueRedGrad.GradientStops.Add(GradBlue)

 

 

        Dim GradRed As New GradientStop()

        GradRed.Color = ColorHelper.Red

        GradRed.Offset = 1

        brBlueRedGrad.GradientStops.Add(GradRed)

 

 

        Me.Rectangle1.Fill = brBlueRedGrad

        'end: with basic gradient (from code-behind)

 

 

    End Sub

The above code is very much self-explanatory. All we are doing is creating a "LinearGradientBrush" object, adding a couple of "GradientStop" instances and assigning the brush to Rectangle shape.

Note: "ColorHelper" is a special class which contains shared (static) members with hard-coded RGB values. It has go to almost all of the default Microsoft named colors and is included in the source code attached to this article.

Understanding Brushes in Silverlight: LinearGradientBrush more examples

In previous sections, we have seen a gradient with only two colors. But we can have as many colors as we want to be added as GradientStops to the same brush. we should always make sure, however, that the "Offsets" are between 0 and 1.

Let us test a couple of samples.

Sample 1 (Multiple gradient colors):

        <Rectangle Canvas.Left="40" Canvas.Top="33" Height="100" Name="Rectangle1" Stroke="Black" StrokeThickness="1" Width="200" >

            <Rectangle.Fill>

                <LinearGradientBrush>

                    <GradientStop Color="Blue" Offset="0.25"/>

                    <GradientStop Color="Yellow" Offset="0.5"/>

                    <GradientStop Color="Red" Offset="0.75"/>

                    <GradientStop Color="LimeGreen" Offset="1"/>

                </LinearGradientBrush>

            </Rectangle.Fill>

        </Rectangle>

 

The above would give us the result shown below:

Sample 2 (Gradient Ray):

        <Rectangle Canvas.Left="40" Canvas.Top="33" Height="100" Name="Rectangle1" Stroke="Black" StrokeThickness="1" Width="200" >

            <Rectangle.Fill>

                <LinearGradientBrush>

                    <GradientStop Color="Blue" Offset="0.45"/>

                    <GradientStop Color="Yellow" Offset="0.5"/>

                    <GradientStop Color="Blue" Offset="0.55"/>

                </LinearGradientBrush>

            </Rectangle.Fill>

        </Rectangle>

 

The above would deliver the result shown below:

Sample 3 (Half cut Gradient):

        <Rectangle Canvas.Left="40" Canvas.Top="33" Height="100" Name="Rectangle1" Stroke="Black" StrokeThickness="1" Width="200" >

            <Rectangle.Fill>

                <LinearGradientBrush>

                    <GradientStop Color="Blue" Offset="0.55"/>

                    <GradientStop Color="Yellow" Offset="0.5"/>

                    <GradientStop Color="Blue" Offset="0.55"/>

                </LinearGradientBrush>

            </Rectangle.Fill>

        </Rectangle>

 

The above would give the result shown below:

 

In my upcoming articles, we will see more examples of Silverlight 4.0 development. I hope you enjoyed the article. Any suggestions, bugs, errors, enhancements etc. are highly appreciated at http://jagchat.spaces.live.com

blog comments powered by Disqus
SILVERLIGHT ARTICLES

- With Silverlight Gone, Whither SharePoint?
- Silverlight in the News
- Silverlight Has a Bright Future
- Windows 8 Effects on .Net and Silverlight De...
- Microsoft`s SkyDrive Abandons Silverlight
- Silverlight Developers Unhappy with Windows ...
- Best Silverlight Examples
- How to install Silverlight for Windows Phone
- Microsoft Reveals Silverlight 5 Features
- Silverlight News: SRS and Microsoft to Bring...
- Silverlight 4.0: Paging Through Data using D...
- Silverlight 4.0: Navigating Data Using Domai...
- Silverlight 4.0: Filtering Data Using Domain...
- Silverlight 4.0: Sorting and Grouping Data w...
- Silverlight 4.0: Query Parameters of DomainD...

ASP Web Hosting ASP.Net Web Hosting Windows Web Hosting
 
 
 

ASP Free Forums 
 RSS  Tutorials RSS
 RSS  Forums RSS
 RSS  All Feeds
Site Map 
Request Media Kit
Write For Us Get Paid 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Privacy Policy 
Support 


© 2003-2012 by Developer Shed. All rights reserved. DS Cluster 9 - Follow our Sitemap
Most Popular Topics
All ASP.Net Tutorials