Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
193 views
in Technique[技术] by (71.8m points)

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

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 this formula, I need to know the Maximum Digit Width of the Normal font, which is the pixel width of the widest numeric digit. The OpenXML specification gives this example as a clarification:

Using the Calibri font as an example, the maximum digit width of 11 point font size is 7 pixels (at 96 dpi).

I have checked that this is correct by visually examining a Calibri 11-point digit and it is indeed 7 pixels wide. So, I am trying to create a method that will return the maximum digit width for any font / size.

I have followed the recommendations made in this question, but it doesn't produce the results I am expecting.

Here's my test code:

var font = new Font("Calibri", 11.0f, FontStyle.Regular);

for (var i = 0; i < 10; i++)
{
    Debug.WriteLine(TextRenderer.MeasureText(i.ToString(), font));
}

This reports that all digits have a width of 15.

Any suggestions please?

Thanks, Tim

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

TextRenderer is not always accurate the way you would expect:

From MSDN: http://msdn.microsoft.com/en-us/library/8wafk2kt.aspx

For example, the default behavior of the TextRenderer is to add padding to the bounding rectangle of the drawn text to accommodate overhanging glyphs

Do you have a Graphics object or a Control object? If you are using these you can get accurate restults the way you would expect.

Take a look at http://msdn.microsoft.com/en-us/library/6xe5hazb(VS.80).aspx


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...