How to: Paint an Area with an Image
This example shows how to use the ImageBrush class to paint an area with an image. An ImageBrush displays a single image, which is specified by its ImageSource property.
The following example paints the Background of a button by using an ImageBrush.
<!-- This example shows how to use an ImageBrush to paint shapes and controls. --> <Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Background="White"> <StackPanel Margin="20"> <!-- Sets the button's Background property with an ImageBrush. The resulting button has an image as its background. --> <Button Foreground="White" FontWeight="Bold" FontSize="16pt" FontFamily="Verdana" Content="Berries" Padding="20" HorizontalAlignment="Left"> <Button.Background> <ImageBrush ImageSource="sampleImages\berries.jpg" /> </Button.Background> </Button> </StackPanel> </Page>
By default, an ImageBrush stretches its image to completely fill the area that you are painting. In the preceding example, the image is stretched to fill the button, possibly distorting the image. You can control this behavior by setting the Stretch property of TileBrush to Uniform or UniformToFill, which causes the brush to preserve the aspect ratio of the image.
If you set the Viewport and TileMode properties of an ImageBrush, you can create a repeating pattern. The following example paints a button by using a pattern that is created from an image.
<!-- This example shows how to use an ImageBrush to paint shapes and controls. --> <Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Background="White"> <StackPanel Margin="20"> <!-- Sets the button's Background property with an ImageBrush. The resulting button has an image as its background. --> <Button Foreground="White" FontWeight="Bold" FontSize="16pt" FontFamily="Verdana" Content="Berries" Padding="20" HorizontalAlignment="Left"> <Button.Background> <!-- The ImageBrush's Viewport and TileMode are set to produce a pattern from the image. --> <ImageBrush Viewport="0,0,0.5,0.5" TileMode="FlipXY" ImageSource="sampleImages\berries.jpg" /> </Button.Background> </Button> </StackPanel> </Page>
For more information about the ImageBrush class, see Painting with Images, Drawings, and Visuals.
This code example is part of a larger example that is provided for the ImageBrush class. For the complete sample, see ImageBrush Sample.