WPF Text Measurement Units
The WPF text team has seen some people get confused about what units WPF uses when measuring text. Samer, a developer on the WPF text team, and I have created this post to try and shed some light on this subject. The first part of this post is very straight forward, whereas the end will only be useful for those of you who are extensively using WPF text APIs.
WPF supports multiple units for text measurement. The units that can be used are “px” (device independent pixels), “in" (inches), "cm" (centimeters), "pt" (points). If you do not specify the unit of measurement, WPF defaults to px.
<TextBlock FontSize="24">Hello World</TextBlock>
To force WPF to use a different unit of measurement, just append the unit abbreviation to the FontSize.
<TextBlock FontSize="24pt">Hello World</TextBlock>
Device Independent Pixels & Physical Pixels
In accordance with WPF’s resolution independence, the framework measures objects in device independent pixels. These device independent pixels can have different sizes than physical pixels.
1 device independent pixel = 1/96 inch.
1 physical pixel = 1/DPI (dependent on the system DPI)
Default system settings usually choose a DPI of 96 so these two types of pixels come out to be the same size. If this is not the case, it is easy to convert between the two types of pixels.
physical pixels = DPI/96 * device independent pixels
device independent pixels = 96/DPI * physical pixels
Notice that as the DPI increases, so does the number of physical pixels which compose one device independent pixel. Hence, objects that have their sizes specified in device independent pixels get larger as the system DPI increases.
A point (pt) is also a common unit of measurement for fonts.
1pt = 1/72 inches
Converting between points and device independent pixels is also easy.
pt = 72/96 device independent pixels
device independent pixels = 96/72 pt
Remember objects which are measured in device independent pixels get larger as system DPI increases? This is true for text. Since there is a constant ratio between point sizes/device independent pixels, if the point size of text is held constant while the system DPI is increased, the size of the rendered text will grow.
Uses For Font Units
Aside from knowing how to correctly set FontSize, the above knowledge could be helpful in understanding the values that WPF text APIs, such as FormattedText or TextFormatter, use and return for the different text measurements. The metrics returned from these APIs are in device independent pixel (eg. some properties of GlyphTypeface including Baseline, CapsHeight, XHeight). When interacting with these APIs make sure that you convert to device independent pixels from whatever unit your font is measured in, or visa versa.
- Samer and Chipalo