Converting between WPF font size and "standard" font size

19,921

Solution 1

WPF uses pixels as its default unit for font size. The mapping between points (probably what you mean when you say "standard" font size) and pixels is: 1 pt = (96/72) px

This gives us a simple conversion function:

public static double PointsToPixels(double points)
{
    return points*(96.0/72.0);
}

See this question for more details.

Solution 2

Another method for conversion if you're going from point to WPF double is to use the System.Windows.FontSizeConverter class:

double sizeForWpf = (double) new FontSizeConverter().ConvertFrom("10pt");
Share:
19,921

Related videos on Youtube

devios1
Author by

devios1

I am a coder: an architect of thought. My name is Logan. I am the founder and sole employee of The Little Software Company. My current project is developing a textual layout language to replace Auto Layout and Interface Builder (ambitious huh?). I'm currently working for Quetzal POS on our next-gen iPad based point of sale.

Updated on October 27, 2020

Comments

  • devios1
    devios1 over 3 years

    I've noticed in WPF, the default font size of 12 points is roughly equivalent to 9 points in "normal" applications (e.g. WordPad), 10 pt in WPF is roughly 7 pt standard, and when I try to match the default font size of 10 pt in WordPad in WPF, I've found 13 is the closest.

    First of all, why does WPF use such bizarre non-standard font sizes, and secondly, is there a reliable way to convert between the two?

    My reason for asking is I want to build a font size menu with "standard" font sizes of 9, 10, 12, 14, 16, 18, 24, 36, 48, but I'm pretty sure if I use those actual values they will be wildly off.

  • devios1
    devios1 almost 14 years
    Thanks! That does appear to be the missing key. I also see I can specify font sizes with a "qualified double" and specify points as the unit, however I wonder how to do that from code.
  • Kevin Shea
    Kevin Shea almost 12 years
    Worth pointing out that WPF documentation confuses the matter considerably by referring to these 1/96 inch pixels as "em units" which is completely different to the typographical meaning of "em" (as used with CSS)
  • B.O.B.
    B.O.B. almost 5 years
    I was curious to see if Windows DPI mattered so I dug into the .Net reference source, and it does not. The FontSizeConverter uses the LengthConverter to convert from a string to double, and that has the following array: static private double[] PixelUnitFactors = { 1.0, // Pixel itself 96.0, // Pixels per Inch 96.0 / 2.54, // Pixels per Centimeter 96.0 / 72.0, // Pixels per Point };