Disabling antialiasing on a WPF image

Bob picture Bob · Nov 15, 2009 · Viewed 12k times · Source

I'm writing a small Login dialog, and have embedded a banner at the top of the dialog for aesthetic reasons. All went well, except that by default, WPF anti aliases the entire image, making the text that was contained within it frustrating blurry.

After a bit of searching, the first few pages of results showed that it's common belief that anti aliasing cannot be disable in WPF. Can any confirm, or otherwise deny this?

It's a minor issue for me - I'll take the text out of the image and instead superimpose a label with the same text on top of the background image to achieve the same effect (though I must admit, it's a bit annoying).

Thanks, Rob

Answer

Ray Burns picture Ray Burns · Nov 16, 2009

As far as I know, WPF always does anti-aliasing when scaling a bitmap. However you should be able to accomplish your goal by avoiding the bitmap scaling.

There are two steps:

  1. Set SnapsToDevicePixels="true" on your image
  2. Set a ScaleTransform on your image to scale it so that one device pixel = one bitmap pixel

To compute the needed ScaleTransform, compute your screen's DPI like this:

var DPI = Win32Functions.GetSystemMetrics(SM_CYICON) / SystemParameters.IconHeight * 96;

and then for the bitmap, do:

var scale = bitmapDPI / DPI;
var transform = new ScaleTransform(scale, scale);

This will cause your bitmap's pixels to exactly match with the device pixels. WPF will not stretch the bitmap, so there should be no anti-aliasing.

If you do want to stretch your image on high DPI screens but do so without anti-aliasing (eg double all pixels), just stretch the bitmap in your own code using whichever algorithm you like and use the above with the stretched bitmap.