Home > Net >  C# WPF Image on Button cut off
C# WPF Image on Button cut off

Time:06-17

I Created a style for my Buttons:

<Style TargetType="Button">
    <Setter Property="Height" Value="20"></Setter>
    <Setter Property="Width" Value="100"></Setter>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate>
                <Border>
                    <Border.Style>
                        <Style>
                            <Setter Property="Border.Background">
                                <Setter.Value>
                                    <ImageBrush ImageSource="/myTool.GUI;component/Resources/Button not clicked.png"/>
                                </Setter.Value>
                            </Setter>
                            <Style.Triggers>
                                <Trigger Property="Border.IsMouseOver" Value="True">
                                    <Setter Property="Border.Background">
                                        <Setter.Value>
                                            <ImageBrush ImageSource="/myTool.GUI;component/Resources/Button clicked.png"/>
                                        </Setter.Value>
                                    </Setter>
                                </Trigger>
                            </Style.Triggers>
                        </Style>
                    </Border.Style>
                    <ContentPresenter Content="{TemplateBinding Button.Content}" VerticalAlignment="Center" HorizontalAlignment="Center"/>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

if i use know a Button in my Windows it looks good in the Designer: Button in Designer

But if i start my Application it looks like this: Button in Live Mode

Why is the left and right side cut off?

Original Image: enter image description here

CodePudding user response:

To me, is about the original image, which is not well-tailored for the desired size (e.g. 20x20px). If I try to resize it using Paint or another app, the result is the same as the WPF rendering.

In particular, I think it's the border too thin. You have a 341px wide image with just 7px thick border. That is a 7 / 341 = 0.0205 ratio.

Now, when you scale down to 20px wide, the border become 20 * 0.0205 = 0.4px. So, less than a single pixel! can't get a decent result that way.

That being said, you could try to improve the result by adjusting the RenderingOptions properties. For instance, you could try the following:

<ImageBrush ImageSource="..." 
    RenderOptions.BitmapScalingMode="HighQuality" 
    RenderOptions.EdgeMode="Aliased"
/>
  • Related