zetar
zetar

Reputation: 1233

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?

Upvotes: 0

Views: 47

Answers (2)

Andy
Andy

Reputation: 12276

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.

Upvotes: 1

zetar
zetar

Reputation: 1233

This solved the problem: I cut the image so that it was the exact same size as the canvas that it was going into. What's happening is that loading a PNG from disk into a Canvas will stretch the image to fit the destination rect. There doesn't appear to be anyway to change this so it will just crop or 'not stretch' like doing it via XAML. If there is a way to specify 'no stretch', I haven't found it.

Upvotes: 0

Related Questions