Search code examples
c#drawingcalculation

How to calculate float value from string


I don't know how to calculate float value from string

float x = 300.0F;
Dictionary<short, string> stringDict = new Dictionary<short, string>();
Dictionary<short, string> whiteSpace = new Dictionary<short, string>();

string row1 = new String(' ', 67);
whiteSpace.Add(1, row1);
stringDict.Add(1, rtBox.Substring(12, 31).Replace("\n", " "));

graphicsObj.DrawString(whiteSpace[i] + stringDict[i], drawFont, drawBrush, x, y, drawFormat);

Expected output would be :

graphicsObj.DrawString(stringDict[i], drawFont, drawBrush, x + whiteSpace[i] float lenght, y, drawFormat);

How can I calculate this float value so I can omit drawing whitespaces ?

EDIT 1: below code doesnt work, its not moving drawing in x axis.

for (short i = 1; i <= 28; i++)
{
     SizeF rowSize = graphicsObj.MeasureString(whiteSpace[i], drawFont);
     float widthRow = rowSize.Width;
     graphicsObj.DrawString(stringDict[i], drawFont, drawBrush, x + widthRow, y, drawFormat);
      y += 15.0F;
}

Solution

  • If you want to calculate the size of the string, you can try with MeasureString, however, according this question, this will not work for a string with only empty spaces. As a workaround, you could try to add a character at the end of your empty string or simply replace the empty space for another character to get the measure, for example:

    string row1 = new String(' ', 66) + "#";
    SizeF rowSize = graphicsObj.MeasureString(row1, drawFront);
    float width = rowSize.Width;
    float height = rowSize.Height;