Search code examples
wpfimagebackgrounduser-controls

How to scale the imageBrush of the background of an user control?


I have a user control in which I want to add an image as background. I am using this code:

<UserControl.Background>
    <ImageBrush ImageSource="x:\myLogo.png"/>
</UserControl.Background>

The problem is that I don't find the way to scale the image, because it fills the user control and doesn't keep the proportions. I cannot find any way to scale and set another properties of the image, except for the opacity.

So, how I could scale and set the fill options of the image?

Thanks.


Solution

  • ImageBrush has the Stretch property to define how to fit the content using the Stretch enumeration:

    Describes how content is resized to fill its allocated space

    <ImageBrush ImageSource="../Image.jpg"/>
    

    No stretch property set

    <ImageBrush ImageSource="../Image.jpg" Stretch="None"/>
    

    Stretch None

    <ImageBrush ImageSource="../Image.jpg" Stretch="Uniform"/>
    

    Stretch Uniform

    <ImageBrush ImageSource="../Image.jpg" Stretch="UniformToFill"/>
    

    Stretch UniformToFill

    Further cropping, shaping or scaling adjustments can be done by using the Viewbox and Viewport properties like described in this tutorial.