Blurred Images in WPF

Bitmaps and icons displayed using WPF often have a very annoying blur effect caused by WPF trying to draw the image with sub pixel precision.

Let’s take the following image:

The image is diaplyed in the WPF window using this XAML:

<Image Source="blurexample.png" Stretch="None" Margin="5.0"
VerticalAlignment="Top" HorizontalAlignment="Left"/>

But if we set it’s margin to 5.5 pixels (or place the image after something that can take non-integral number of pixels to draw, like text) we get this:

That is obviously unacceptable, but how can we overcome this? The best solution I’ve found is the Bitmap class described in this post.

But the bitmap class has one limitation making it unfit for displaying icons in a GUI, it will always draw the image in the same pixel size while the rest of the GUI scales depending on the screen’s DPI setting, fortunately this is easy to fix.

Replace the MeasureCore method in the Bitmap class with this code:

        protected override Size MeasureCore(Size availableSize)
        {
            Size measureSize = new Size();

            BitmapSource bitmapSource = Source;
            if(bitmapSource != null)
            {
                measureSize = new Size(bitmapSource.PixelWidth, bitmapSource.PixelHeight);
            }

            return measureSize;
        }

This will make the Bitmap display the bitmap aligned to the pixel grid but still scale the image for high DPI screens, on standard normal DPI screens the images will be crisp and clear, the downside is that this will make the images blurred in most high DPI scenarios but at least the images will remain the same size relative to the rest of the GUI.

posted @ Thursday, November 20, 2008 3:58 PM

Comments on this entry:

# re: Blurred Images in WPF

Left by MaMazav at 6/7/2013 4:24 PM

Starting from .NET 4 you can use:
RenderOptions.SetBitmapScalingMode(image1, BitmapScalingMode.NearestNeighbor);

# re: Blurred Images in WPF

Left by Sergey at 4/7/2016 7:32 PM

MaMazav

Thanks, that was helpful

Your comment:



 (will not be displayed)


 
 
Please add 3 and 1 and type the answer here: