XAML ImageBrush

Learn how to an use an ImageBrush to fill graphics objects with images.
  • 3480
An image brush uses an image as fill color to fill graphics objects such as a recntagle, ellipse, and path. The <ImageBrush/> represents the image brush in XAML.  The BitmapSource property represents the image used to fill the brush.
 
Creating an Image Brush
 
The following code creates a brush with sunset.jpg. Once a brush is created, you can use it to fill graphics objects.
 
 <ImageBrush BitmapSource="C:\sunset.jpg" />
 
For example, the following code fills a rectangle with an ImageBrush.
 
 <Window xmlns="http://schemas.microsoft.com/winfx/avalon/2005"
  xmlns:x="http://schemas.microsoft.com/winfx/xaml/2005">
  <Rectangle Width="200" Height="100" Stroke="Black" StrokeThickness="3"> 
      <Rectangle.Fill>
         <ImageBrush BitmapSource="C:\sunset.jpg" />
      </Rectangle.Fill>
  </Rectangle>
</Window>
 
The output looks like Figure 1.

 ImageBrushImg1.gif

Image 1. Rectangle filled with image brush.

The Stretch Enumeration
 
The Stretch enumeration specifies the stretch of the image. The Stretch attribute of ImageBrush is used to set the stretch of the brush. It has four values - None, Fill, Uniform, and UniformToFill.
 
None does not stretch image. The following code uses None stretch.
 
 <Rectangle Width="200" Height="100" Stroke="Black" StrokeThickness="3"> 
  <Rectangle.Fill>
         <ImageBrush Stretch="None" BitmapSource="C:\ButterFly.jpg" />
 </Rectangle.Fill>
</Rectangle>

The output is a rectangle filled with original image size.

 ImageBrushImg2.gif

Fill fill image in the whole brush. The following code uses Fill stretch.

 <Rectangle Width="200" Height="100" Stroke="Black" StrokeThickness="3"> 
 <Rectangle.Fill>
         <ImageBrush Stretch="Fill" BitmapSource="C:\ButterFly.jpg" />
 </Rectangle.Fill>
</Rectangle>
ImageBrushImg3.gif
Uniform fills brush with the native aspect ration. The following code uses Uniform stretch.
 
 <Rectangle Width="200" Height="100" Stroke="Black" StrokeThickness="3"> 
<Rectangle.Fill>
         <ImageBrush Stretch="Uniform" BitmapSource="C:\ButterFly.jpg" />
 </Rectangle.Fill>
</Rectangle>

The output is a rectangle filled with image but kept the original aspect ratio.
  ImageBrushImg4.gif
UniformToFill fills brush with the native aspect ration. The following code uses UniformToStretch stretch.
 
 <Rectangle.Fill>
         <ImageBrush Stretch="UniformToFill" BitmapSource="C:\ButterFly.jpg" />
 </Rectangle.Fill>
</Rectangle>
 
The output is a rectangle filled with but also kept the original aspect ratio.

 ImageBrushImg5.gif

Summary

In this article, I discussed XAML ImageBrush element and how to use it in your applications.
 
Further Readings
 
You may also want to read these related articles.
Ask Your Question 
 
Got a programming related question? You may want to post your question here
 

© 2019 DotNetHeaven. All rights reserved.