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: