Click here to Skip to main content
15,890,438 members
Please Sign up or sign in to vote.
3.00/5 (1 vote)
See more:
C#
string text = "aaaaaa";
float width1 = e.Graphics.MeasureString(
    text,
    new Font("calibri", 12, GraphicsUnit.Pixel)).Width;

float width2 = 0;
for (int i = 0; i < text.Length; i++)
{
    width2 += e.Graphics.MeasureString(
        text[i].ToString(),
        new Font("calibri", 12, GraphicsUnit.Pixel)).Width;
}

i want to measure size of Chracter.
why width2 and width1 is not exactly same?
and how can i measure Character rightway?

What I have tried:

this is my best idea... i guess.
Posted
Updated 21-Aug-16 2:22am
v2
Comments
Ralf Meier 21-Aug-16 6:51am    
You are not meassuring the width of each character inside the string - for that you should use the sub-method .SubString from your string-variable ...

1 solution

Because the width of a string is not the sum of the widths of all teh characters, except in non-proportional (or fixed width) fonts.
In a fixed width font all characters are the same width, so the string is the width of a character times the number of characters:
WIIIIILL
12222234

But in a proportional font:
WIIIIILL
12222234

The characters aren't the same width.
That doesn't cause your problem, but it starts to indicate why it's a problem - becuase proportional fonts can have other features, such as pair-kerning:
WAWAWA
121212

WAWAWA
121212

What happens here is that the W and the A are "tucked together" because part of the A "fits" under the W instead of waiting for it to finish and a small gap added:
WAWANAWA
(there are other effects as well, but that is the easiest to show)
So you can't just measure each character and assume the string will be the same length!

[edit]line breaks added for readbility[/edit]
 
Share this answer
 
v2
Comments
Mehdi Gholam 21-Aug-16 7:14am    
I was about to say the same thing, beat me to it, 5'ed!
Maciej Los 21-Aug-16 16:21pm    
5ed!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900