SnapsToDevicePixels not working with images?

I am having a problem with bitmaps in WPF. When the image container starts at a position that is not an integer, the image does not seem to match the value of SnapsToDevicePixels .

Code example:

 <Window x:Class="BlurryImage.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Height="110" Width="200"> <StackPanel Orientation="Horizontal" VerticalAlignment="Center"> <Button SnapsToDevicePixels="True"> <Image SnapsToDevicePixels="True" Source="i16.png" Stretch="None"/> </Button> <Button SnapsToDevicePixels="True" Margin="10.333333,0,0,0"> <Image SnapsToDevicePixels="True" Source="i16.png" Stretch="None"/> </Button> </StackPanel> </Window> 

(Note the value of the left margin: 10.333333.)

Here, the i16.png image is a simple 16x16 raster map with a resolution of 96 DPI with thin vertical lines: image here . (My system resolution is 96 DPI, Windows XP, .NET 4)

When I run the program, the first image is sharp and the second is blurry: blurry image screenshot

Various sources, including some here in stackoverflow, offer different workarounds. (For example, these messages are [1] , [2], and [3] .) I tried workarounds and they seem to work. Using UseLayoutRounding="true" in the main window makes both images sharp. Using RenderOptions.BitmapScalingMode="NearestNeighbor" in the image makes it clear.

The question is why SnapsToDevicePixels="True" does not work without workarounds? Is this a bug in WPF, or am I using it incorrectly?

+4
source share
1 answer

From this blog post :

SnapsToDevicePixels

WPF expected that there would be times when people would like to align with a pixel grid instead of using subpixel precision. You can set the SnapsToDevicePixels property on any UIElement. This will cause us to try to render in a pixel grid, but there are quite a few cases that do not work - including images. We will strive to improve this in the future.

So this is just a known limitation of what SnapsToDevicePixels can do.

+4
source

All Articles