Silverlight Tips provides simple and useful tutorials and tips with real life examples, live demos and sample codes to download.
About authors:
Damon Serji
Damon Serji,
Silverlight developer working at Metia in London.
Gavin Wignall
Gavin Wignall,
Interactive Design Lead, working in design for over 10 years, the last 3 being in Silverlight.
Allan Muller
Allan Muller,
Developer, working on various types of Silverlight and WCF projects.
Recent comments

In this example I will demonstrate how to use ImageBrush to fill area of shapes like rectangle or ellipse with an image.

In order to fill the area of a control like Rectangle control, we need to create an instance of type BitmapImage, and this is not possible if we do not have a Uri which points to a real image file.

So first, I create an Uri pointing to an image which I had put in the “images” folder in my Silverlight application project.

Hint: try to use Uri.TryCreate to create your Uri as by this way you stop your application from breaking if the path you gave your Uri was not valid or did not exist.

Second, create a new instance of BitmapImage and assign your Uri to its value.

Uri imageUri;
BitmapImage image = null;

if (Uri.TryCreate("images/SilverlightTips.jpg", UriKind.RelativeOrAbsolute, out imageUri))
{
    image = new BitmapImage(imageUri);
}

Now you can create a new instance of ImageBrush and assign your created BitmapImage to its ImageSource value:

ImageBrush imageBrush = new ImageBrush();
imageBrush.ImageSource = image;

Finally, using .Fill method on your Rectangle control fill the entire rectangle (or any other shapes your object is) with your ImageBrush. And here is how your final code should look like:

Uri imageUri;
BitmapImage image = null;

if (Uri.TryCreate("images/SilverlightTips.jpg", UriKind.RelativeOrAbsolute, out imageUri))
{
    image = new BitmapImage(imageUri);
}
if (image != null)
{
    ImageBrush imageBrush = new ImageBrush();
    imageBrush.ImageSource = image;
    Logo.Fill = imageBrush;
    LogoEllipse.Fill = imageBrush;
    LogoRectangle.Fill = imageBrush;
}

Download this project from CodePlex from here. Here it is working:

Posted by Damon Serji on 28. September 2009 13:42 under: Intermediate
 with 2 Comments

Comments

Pingback from silverlightweb.com.cn

How to display image using ImageBrush Silverlight Web

Posted 12/1/2009 7:06:40 AM

Pingback from 72.unlockiphone30.net

Cdk5 P25 P35 Neurofibrillary Tangles, Used Komatsu P3500

Posted 5/20/2010 9:41:43 PM

Add comment


(Will show your Gravatar icon)

biuquote
  • Comment
  • Preview