Using ImageBrush In WPF

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.

  1. <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 21 creates a rectangle shape sets the Fill property to an ImageBrush.

  1. <Rectangle Width="200" Height="100" Stroke="Black" StrokeThickness="4">  
  2.     <Rectangle.Fill>  
  3.         <ImageBrush ImageSource="dock.jpg" />  
  4.     </Rectangle.Fill>  
  5. </Rectangle>  

Listing 21

The output looks like Figure 26.

A shape filled with an image brush
Figure 26. A shape filled with an image brush

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

  1. ///<summary>  
  2. /// Fills a rectangle with an ImageBrush  
  3. ///</summary>  
  4. publicvoid CreateAnImageBrush() {  
  5.     // Create a Rectangle  
  6.     Rectangle blueRectangle = newRectangle();  
  7.     blueRectangle.Height = 100;  
  8.     blueRectangle.Width = 200;  
  9.     // Create an ImageBrush  
  10.     ImageBrush imgBrush = newImageBrush();  
  11.     imgBrush.ImageSource = newBitmapImage(newUri(@ "Dock.jpg", UriKind.Relative));  
  12.     // Fill rectangle with an ImageBrush  
  13.     blueRectangle.Fill = imgBrush;  
  14.     // Add Rectangle to the Grid.  
  15.     LayoutRoot.Children.Add(blueRectangle);  
  16. }  

Listing 22


Mindcracker
Founded in 2003, Mindcracker is the authority in custom software development and innovation. We put best practices into action. We deliver solutions based on consumer and industry analysis.