Reader Level:

Image Brush in Silverlight

By Mahesh Chand on Mar 02, 2009
This article demonstrates how to use an ImageBrush in Silverlight and XAML to view images in C#.
  • 0
  • 0
  • 26200

This article demonstrates how to create and use an image brush in Silverlight using XAML and C#.

Image Brush

An image brush paints an area with an image. The ImageSource property represents the image to be used during the painting by an image brush. The ImageBrush object represents an image brush. 

Creating an Image Brush

The ImageBrush element in XAML creates an image brush. The ImageSource property of the ImageBrush represents the image used in the painting process.

The following code snippet creates an image brush and sets the ImageSource property to an image.

<ImageBrush ImageSource="dock.jpg" />

We can fill a shape with an image brush by setting a shape's Fill property to the image brush. The code snippet in Listing 1 creates a rectangle shape sets the Fill property to an ImageBrush.







        <ImageBrush ImageSource="dock.jpg" />



Listing 1

The output looks like Figure 1.


Figure 1

The CreateAnImageBrush method listed in Listing 2 draws same rectangle with an image brush in Figure 1 dynamically.

/// <summary>

/// Fills a rectangle with an ImageBrush

/// </summary>

public void CreateAnImageBrush()


    // Create a Rectangle

    Rectangle blueRectangle = new Rectangle();

    blueRectangle.Height = 100;

    blueRectangle.Width = 200;


    // Create an ImageBrush

    ImageBrush imgBrush = new ImageBrush();


    imgBrush.ImageSource =

        new BitmapImage(new Uri(@"Dock.jpg", UriKind.Relative));


    // Fill rectangle with an ImageBrush

    blueRectangle.Fill = imgBrush;


    // Add Rectangle to the Grid.



Listing 2


In this article, we saw how to create and use an image brush in Silverlight using XAML and C#.

Mahesh Chand

Founder C# Corner, a member-contributions based community founded in 1999 focuses on character, values, learning, sharing, networking and career growth. Mahesh has been awarded prestigious... Read more