Reputation: 1066
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?
Upvotes: 2
Views: 2815
Reputation: 7629
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.
Upvotes: 4