How to measure the pixel width of a digit in a given font / size (C#)

后端 未结 5 1845
闹比i
闹比i 2021-01-04 23:53

I am trying to calculate the pixel width of Excel columns, as described in this post, using the official formula from the OpenXML specification. However, in order to apply t

5条回答
  •  旧巷少年郎
    2021-01-05 00:35

    MeasureText adds padding, the amount is fairly unpredictable although it roughly scales linearly with the font size. The trick is to subtract two measurements to get rid of the padding. This code generated very happy numbers:

            float size = 5;
            for (int ix = 0; ix < 10; ++ix) {
                var font = new Font("Calibri", size, FontStyle.Regular);
                string txt = new string('0', 100);
                SizeF sz1 = TextRenderer.MeasureText("00", font) - TextRenderer.MeasureText("0", font);
                Console.WriteLine("{0} {1:N3}", size, sz1.Width);
                size += 2;
            }
    

    Output:

    5 4.000
    7 5.000
    9 6.000
    11 7.000
    13 9.000
    15 10.000
    17 12.000
    19 13.000
    21 14.000
    23 16.000
    

    That gets you the 7 pixels you're looking for. Beware that you'll have to accommodate TrueType hinting, it can adjust the shape of the digit so that its main stems fall on pixel boundaries. Add at least one pixel.

提交回复
热议问题