Pixel Measurements in WPF

Part of the beauty of the Windows Presentation Foundation is that it is designed to be resolution independent – that is, a WPF application should scale perfectly no matter the system’s DPI setting (excluding any bitmap graphics, which mightn’t look as nice as the vector parts).

Instead of measuring things in pixels, WPF uses Device Independent Units (DIUs). If you only ever use 96 DPI (100%), you won’t notice the difference: at that setting, 1 pixel is the same as 1 DIU. Increase the system DPI, though, and this will no longer hold true. For example, at 120 DPI (125%), 1 DIU will be represented as 1.25 pixels. At 144 DPI (150%), 1 DIU = 1.5 pixels. At 192 DPI (200%), 1 DIU = 2 pixels.

Notice that at 120 DPI and 144 DPI, the number of pixels in 1 DIU is not an integer. In cases like these – when edges fall in the middle of screen pixels – WPF uses anti-aliasing by default. This can, however, result in lines that seem blurry (after all, that’s what anti-aliasing does). If this behaviour is undesirable, one can use UIElement’s SnapsToDevicePixels property.

WPF’s built-in handling of DPI scaling is great: in most cases, it should be transparent to both the programmer and user.

Sometimes, though, one might want to measure lengths in pixels, not DIUs. For example, Keiki’s custom window border for when the DWM (Aero) is disabled needs to be 1 pixel thick at any DPI (this is how the system’s notification area applications look). So, how can we specify this?

First, we need to get the system’s DPI setting:

dpiX and dpiY will hold values like 1.0 (96 DPI), 1.25 (120 DPI), 1.5 (144 DPI) and 2.0 (192 DPI).

To specify a pixel measurement, we simply divide the DIU measurement by the DPI factor (dpiX and dpiY should always be the same – at least in Windows 7 and earlier):

This will make the margin 3 pixels thick at any DPI. (For example, at 120 DPI, dpiX = 1.25. 3 / 1.25 = 2.4 DIUs. 2.4 DIUs will be converted by WPF to 3 pixels.)

Fedir Nepyivoda has a neat solution to this problem: instead of manually converting DIU measurements, he created a PixelBorder control (inheriting from Border) that overrides MeasureOverride. Have a look here.