[imgur deleted image]
The icon on the left is the result of this code:
<Button Height="23" HorizontalAlignment="Left" Margin="12,276,0,0" Name="butto开发者_StackOverflow中文版n1" VerticalAlignment="Top" Width="75">
<StackPanel Orientation="Horizontal">
<Image Source="Resources/add.png" Stretch="None" />
<TextBlock Margin="5,0,0,0" Text="Add" />
</StackPanel>
</Button>
The one on the right is the original image placed beside it using Photoshop. It appears the one added via code is stretched by a pixel causing some distortion. How do I prevent that?
Stretch="None"
should do exactly that. If there is a difference in how the Image is displayed that may be due to pixels ending up "on edge".
You could try setting SnapsToDevicePixels
="True"
to avoid this.
Try using RenderOptions.BitmapScalingMode="NearestNeighbor"
.
You may want to read these:
- My images are blurry! Why isn't WPF's SnapsToDevicePixels working?
- Blurry Bitmaps - Dwayne Need
Adding Stretch = None keeps the image from rezising
<ImageBrush ImageSource="rtgEnhanced.png" AlignmentX="Left" AlignmentY="Bottom" Stretch="None"></ImageBrush>
I can't really see what's going on in your example, but a very common cause of this sort of problem with WPF is the DPI value in the PNG file being something other than 96 (often 72 if it's come from anything with a Mac heritage).
PNG images can have something called a pHYs chunk stored in them. This chunk defines the DPI that the image is intended to be displayed at. If the DPI of the image doesn't match the DPI of the monitor, it will be stretched by WPF in order to make it appear at the "intended" size. This usually (at least for me) is NOT at all what I intended and causes a lot of frustration.
In order to remove the "intended" stretching, one option is to remove the pHYs chunk from the PNG.
You can use a tool like TweakPNG to inspect and remove pHYs.
Alternatively, you can simply save your images with the correct DPI encoded in them, or none at all, presuming that your image editing software supports that.
Actually, NearestNeighbor is going to allow the engine to skip over pixels in the source image when scaling. If there is an option for Linear, that may work better as it means to scale reading pixel by pixel from the source image.
I have only managed to solve this by explicitly setting the width or height. So if you know the image is 48 pixels high do like this:
<Image Source="myImage.png" Height="48" UseLayoutRounding="True"/>
This fixed it for me:
On your root element (i.e. your main window) add this property:
UseLayoutRounding="True"
.
credit
精彩评论