#277 – Images May Have Embedded DpiX and DpiY Information

Even when you specify Stretch=None for an Image control, you may notice that the image does not appear at the expected number of pixels wide/high.  This can happen if the image’s resolution (DPI) doesn’t match your current system DPI.

An image file (e.g. .png or .jpg) contains an image that is a certain number of pixels wide/high.  An image file may also contain embedded DpiX and DpiY (resolution) information.  This resolution information is not present in all image files.

WPF uses this resolution information to calculate the image size in WPF Units as:

  • Width (in WPF Units) = (96 * ImageWidth) / ImageHorizontalDPI
  • Height (in WPF Units) = (96 * ImageHeight) / ImageVerticalDPI

If there is no resolution information in the file, WPF defaults to 96 dpi.

WPF then calculates the image size in pixels as:

  • Width (pixels) = Width (WPF Units) * (SystemDPI / 96)
  • Height (pixels) = Height (WPF Units) * (SystemDPI / 96)

 

Advertisement

#203 – Window Size and Location Are Specified in Device Independent Units

The Window class has Left and Top properties that specify the location on the screen of the left and top sides of the window.  It also has Width and Height properties that specify the window’s size.  All of these are expressing in device independent units.

If the current DPI setting is 96 dpi (dots per inch), the WPF units are equivalent to pixels.  I.e. A window specified as 96 units high would appear as 1 inch high.  If the DPI setting is different, the specified WPF units are scaled by dpi/96 to get the resulting pixel value.

In other words:    # pixels = (# WPF Units) * (DPI / 96)

The reason for this is so that WPF applications will appear at roughly the same dimensions on various monitors, regardless of the pixel density.

#23 – WPF Units

In Windows Forms, control sizes are specified using pixels.  In WPF,  sizes are specified using WPF Units.

1 WPF unit = 1/96 inch.  This means at 96 dpi (typical), 1 WPF Unit = 1 pixel.

But this means that at 120 dpi, 1 WPF unit = 1.25 pixels.  (120/96)

Because everything in a WPF GUI using WPF units for sizing, all controls are properly resized based on the system DPI.  The reason for this is so that they can appear to be the same physical size on a device that happens to have a higher pixel density (DPI).  A 96 unit button will be 1″ wide on a 96 dpi device and 1″ wide on a 120 dpi device (because it’s scaled up to 120 pixels).

This same scaling could be done in Windows Forms using a form’s AutoScaleMode property.  But in WPF, it’s automatic.

The full formula:

# pixels = (# WPF Units) * (DPI / 96)