I am trying to scale the background image of a TextBox but it is cropped

时间:2017-04-06 16:46:26

标签: c# wpf background textbox

I have a TextBox in which I want to add an image as background. The first try is this:

<TextBox Text="{Binding Titulo}" Height="Auto" HorizontalAlignment="Stretch" Margin="5,5,5,5" Name="txtTitulo" VerticalAlignment="Stretch"
         TextAlignment="Center"
         FontSize="30"
         Padding="0,20,0,0"
         FontWeight="Heavy"
         BorderBrush="red"
         BorderThickness="5">
    <TextBox.Background>
        <ImageBrush ImageSource="../Imagenes/Logo (233x251) - fondo  transparente (test).png" AlignmentX="Center"  Stretch="None" AlignmentY="Center">
        </ImageBrush>
    </TextBox.Background>
</TextBox>

The result in this case is this:

enter image description here

If I use this code, that uses transform:

<TextBox Text="{Binding Titulo}" Height="Auto" HorizontalAlignment="Stretch" Margin="5,5,5,5" Name="txtTitulo" VerticalAlignment="Stretch"
         TextAlignment="Center"
         FontSize="30"
         Padding="0,20,0,0"
         FontWeight="Heavy"
         BorderBrush="red"
         BorderThickness="5">
    <TextBox.Background>
        <ImageBrush ImageSource="../Imagenes/Logo (233x251) - fondo  transparente (test).png" AlignmentX="Center"  Stretch="None" AlignmentY="Center">
            <ImageBrush.Transform>
                <ScaleTransform ScaleX="0.5" ScaleY="0.5" CenterX="0" CenterY="0" />
            </ImageBrush.Transform>
        </ImageBrush>
    </TextBox.Background>
</TextBox>

The result is this:

enter image description here

The image that I want to scale is this:

enter image description here

It seems that when it scales, reduce the size, but it crops the image to the size of the TextBox.

What I want to do it is scale the image to see the complete image, but I am not be able to get it.

1 个答案:

答案 0 :(得分:1)

您需要使用Uniform作为Stretch属性的值。像这样:

Stretch="Uniform"

所以,你的代码看起来像这样:

<TextBox Text="{Binding Titulo}" Height="Auto" HorizontalAlignment="Stretch" Margin="5,5,5,5" Name="txtTitulo" VerticalAlignment="Stretch"
         TextAlignment="Center"
         FontSize="30"
         Padding="0,20,0,0"
         FontWeight="Heavy"
         BorderBrush="red"
         BorderThickness="5">
    <TextBox.Background>
        <ImageBrush ImageSource="../Imagenes/Logo (233x251) - fondo  transparente (test).png" AlignmentX="Center"  Stretch="Uniform" AlignmentY="Center"/>
    </TextBox.Background>
</TextBox>

Uniform值使图像填充所有可用空间,同时保持其原始比例。