Preserve the Aspect Ratio of an Image Used as a Background

How to: Preserve the Aspect Ratio of an Image Used as a Background

 

This example shows how to use the Stretch property of an ImageBrush in order to preserve the aspect ratio of the image.

By default, when you use an ImageBrush to paint an area, its content stretches to completely fill the output area. When the output area and the image have different aspect ratios, the image is distorted by this stretching.

To make an ImageBrush preserve the aspect ratio of its image, set the Stretch property to Uniform or UniformToFill.

Example

The following example uses two ImageBrush objects to paint two rectangles. Each rectangle is 300 by 150 pixels and each contains a 300 by 300 pixel image. The Stretch property of the first brush is set to Uniform, and the Stretch property of the second brush is set to UniformToFill.

The following illustration shows the output of the first brush, which has a Stretch setting of Uniform.

ImageBrush with Uniform stretching

The next illustration shows the output of the second brush, which has a Stretch setting of UniformToFill.

ImageBrush with UniformToFill stretching

Note that the Stretch property behaves identically for the other TileBrush objects, that is, for DrawingBrush and VisualBrush. For more information about ImageBrush and the other TileBrush objects, see Painting with Images, Drawings, and Visuals.

Note also that, although the Stretch property appears to specify how the TileBrush content stretches to fit its output area, it actually specifies how the TileBrush content stretches to fill its base tile. For more information, see TileBrush.

This code example is part of a larger example that is provided for the ImageBrush class. For the complete sample, see ImageBrush Sample.

Show:
© 2016 Microsoft