Search code examples
c#wpfcanvasbackgroundpng

Loading a PNG at runtime is creating a different height than the PNG loaded with XAML


I've never seen this before. If I set the background of a canvas like this:

<Canvas.Background>
    <ImageBrush  ImageSource="Combined Victorian.png"  Stretch="None" AlignmentX="Left" AlignmentY="Top" />
</Canvas.Background> 

It looks like this at runtime:

enter image description here

Great! Just what I want. But later, on a button press, I'm switching between 2 images for the Canvas background. And when I load the exact same image like this:

ImageBrush brush = new ImageBrush();
brush.ImageSource = new BitmapImage(new Uri(@"Images\Combined Victorian.png", UriKind.Relative));
MainCanvas.Background = brush;

It's squished and looks like this:

enter image description here

How might I solve this?


Solution

  • Your first piece of markup sets Stretch="None" on the imagebrush.

    Your code does not.

    This is the difference.

    Imagebrush inherits from tilebrush and you can see the stretch property on that:

    https://learn.microsoft.com/en-us/dotnet/api/system.windows.media.tilebrush.stretch?view=netframework-4.8#System_Windows_Media_TileBrush_Stretch

    You should probably be setting stretch to uniform if you want to retain aspect ration when the user resizes the window. Like when they start it maximised.