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"
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);
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