2

I have a fixed width (Height is not the problem) label component in C#. Now I want to calculate that approximately how many characters will fit in to that width if font size and font family is provided. I know that every character takes different pixels while rendering so it is not possible to get the exact number of characters. But, I think if we take the letter who takes more no of pixels and calculate considering that letter, we will able to get approximate number of characters that will fit into the fixed width according to font provided. So, if we consider the character 'W' as the widest one then how will I calculate the number of 'W's that will fit in particular width.

I can not use the GDI+ Graphics.MeasureString method since I want it before rendering the character.

When I use the GDI TextRenderer class

SizeF sizeOfW = TextRenderer.MeasureText("W", new Font("DejaVu Sans", 28.0F));

It returns {59.0, 44.0}, which I find is completely wrong, because if I took width of label as 80 px, according to above calculation It will have only one 'W' but it's not the case in reality.

So can anybody tell where I am going wrong?

beppe9000
  • 1,056
  • 1
  • 13
  • 28
ganesh
  • 1,006
  • 14
  • 30
  • 1
    is that label showing more than one 'W' with the samefont? – Uthistran Selvaraj Jan 19 '13 at 06:53
  • It is showing 2 w's which should not be the case because 59 + 59 = 118 and their is a lots of difference between 80 and 118 – ganesh Jan 19 '13 at 07:00
  • 1
    So what will `TextRenderer.MeasureText("WW", new Font("DejaVu Sans", 28.0F))` return for you? – AgentFire Jan 19 '13 at 07:05
  • 1
    [This question](http://stackoverflow.com/questions/1087157/accuracy-of-textrenderer-measuretext-results) and the answers there (also the not accepted answer) could give the right direction – Steve Jan 19 '13 at 10:58

1 Answers1

3

You can use the following:

var g=Graphics.FromHwnd(label1.Handle);
int charFitted, linesFitted;
g.MeasureString(mystring, label1.Font, label1.Size, null, 
                 out charFitted, out linesFitted);

After the execution you will have into charFitted the amout of chars that label1 can show.

Tobia Zambon
  • 7,479
  • 3
  • 37
  • 69
  • Graphics.MeasureString is **not** a substitute for TextRenderer.MeasureText. – Hans Passant Aug 01 '13 at 16:53
  • @HansPassant I don't think OP asks for a substitute of MeasureText, neither he want to necessarily use it. OP wants a solution to calculate how many characters of a given string can be fitted into a label and I think that could be a solution. – Tobia Zambon Aug 02 '13 at 06:34