Friday, November 11, 2011

WPF Text Measurement Units


General Units
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 WorldTextBlock>
24px
To force WPF to use a different unit of measurement, just append the unit abbreviation to the FontSize.

<TextBlock FontSize="24pt">Hello WorldTextBlock>
24pt

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.


Points
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 indevice 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.

No comments:

Post a Comment