Wednesday, November 10, 2010

WPF Quirks: Image gets resized (badly) even when Stretch is set to None

The scenario is that an Image that has its Stretch property set to None still has a different size from the original image source. You check the Padding, the Margin, the VerticalAlignment and HorizontalAlignment properties, you play with the RenderOptions and SnapsToDevicePixels and nothing seems to work. You specify the Width and Height manually and the image is clipped. The problem here, believe it or not, is that the DPI setting of the image source is different from the system DPI setting.

The solution is an ugly thing:

Width="{Binding RelativeSource={RelativeSource Self}, Path=Source.PixelWidth}"
Height="{Binding RelativeSource={RelativeSource Self}, Path=Source.PixelHeight}"/>
So set the Stretch to Fill so that it doesn't fill!

Here is the discussion where I got the solution from: How do I keep an image from being stretched when Stretch="None" doesn't work?.


Anonymous said...


Anonymous said...

Very useful post.
Thank you.

Kai Sellgren said...

This is a hack... the cleaner solution is to fix the DPI issue as I have shown in this StackOverflow answer:

Siderite said...

Of course it is a hack. It is me who you are talking with! :)

Thank you for your solution, but it only works when you have control over the image and/or deployment environment. What would you do if you had some software that takes a user image and then displays it?

Now, it would be grand if you could post a .Net algorithm that does what you described in your StackOverflow answer...

Dallas said...

Siderite, thank you so much for sharing! Really helpful!

Anonymous said...

Great! Thank you!