Well, the short answer to your question:
Is the problem that String.Length and Label.Width have different measure units?
Is "yes".
See here for more information on the Width
property, and here for more information on String.Length
.
Basically: String.Length
refers to the number of characters in the string. "ABC123" would return 6. Control.Width
is a measurement in pixels. And since different fonts appear differently, it would be extremely cumbersome to try and figure out "N characters in X font is Y pixels". (EDIT: And that's assuming you're using a mono-width font. If not, it's even more complex as "iii" is visibly longer than "aaa".)
In regards to your follow-up:
Are there any other ways to handle this?
(EDIT: Changing this part after coming up with an idea in comments)
1) Write the string to an image file
2) Find a suitable library that can determine color from a coordinate or set of coordinates in an image
3) Loop N times over the rows of pixels your image where N = the height of the image
4) Look for lines containing black pixels. We don't want lines that are ALL white as that would just be the "buffer" above and below our text.
5) Iterate over each pixel in the current row and store the X
coordinate of the first black pixel, then store the X
coordinate of every black pixel after the first in a "temporary" variable
6) Store the difference between lastBlackPixel
and firstBlackPixel
in a variable
7) Compare the difference between those two points for every row in your image. If the current difference is greater than largestKnownDifference
then update that variable with the new distance.
That should determine the width of the text. Or maybe iterate each column and store the position of the first black pixel and then the the position of the last column to contain a black pixel? I don't know, I haven't had my coffee yet. Lots of ways to skin a cat.