.NET (295) administrative (41) Ajax (42) AngularJS (2) ASP.NET (144) bicycle (2) books (180) browser (8) C# (133) cars (1) chess (28) CodePlex (10) Coma (8) database (47) deployment (3) Entity Framework (2) essay (110) flash/shockwave (2) flex (1) food (3) friend (2) game (20) idea (5) IIS (8) javascript (82) LInQ (2) Linux (6) management (4) manga (42) misc (669) mobile (1) movies (90) MsAccess (1) murder (2) music (64) mysql (1) news (99) permanent (1) personal (68) PHP (1) physics (2) picture (307) places (12) politics (13) programming (501) rant (120) religion (3) science (43) Sharepoint (3) software (58) space (1) T4 (2) technology (11) Test Driven Development (4) translation (2) VB (2) video (97) Visual Studio (44) web design (45) Windows API (8) Windows Forms (3) Windows Server (4) WPF/Silverlight (63) XML (11)

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:

<Image
Stretch="Fill"
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?.

5 comments:

Anonymous said...

trackback: https://rain75.wordpress.com/2011/03/09/image-correct-size/

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:

http://stackoverflow.com/a/10362776/283055

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!