XAML ImageBrush
Learn how to an use an ImageBrush to fill graphics objects with images.
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.
The output looks like Figure 1.
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.
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>
|
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.
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.
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