Search code examples
c#drawstringvalueconverter

How can i determine the width of a drawn string?


I'm drawing a string using the following:

g.DrawString(somestring, somefont, new SolidBrush(Color.Black), X where it starts, Y where it starts));

Problem:

Sometimes I want to align the drawn string on the left side of a line. But, it doesn't work if I don't know what the string length will be.

Possible but noob solution:

Count the number of chars, multiply for a trial and error value, and subtract it on X position, like this:

string somestring = Convert.ToString(Math.Round(10 * somevalue) / 10) + "m";
int stringcount1 = somestring.Count();
g.DrawString(somestring, somefont, new SolidBrush(Color.Black), X -stringcount1 * trialanderrorvalue, Y));

This doesn't work because, as you can guess, I'm creating a number, and that number can have a decimal separator or not.

And that is the problem, because the decimal separator is not a very wide character, but still counts, it will be sending my string neptune-far from the line. Or I can get a decent trial and error value for a number with a decimal separator, and if eventually the number doesn't have a decimal separator it will be above the line (and ruin the drawing).

Any hints? Possibly forcing the string to have a ,0 in the case that the number is a integer?

Edit:

I've now created a method that will return aSizeF object given a string and a font.

    static SizeF MeasureStringMin(string measureString, Font stringFont, PaintEventArgs e)
    {
        //// Set up string. 
        //string measureString = "Measure String";
        //Font stringFont = new Font("Arial", 16);

        // Measure string.
        SizeF stringSize = new SizeF();

        stringSize = e.Graphics.MeasureString(measureString, stringFont);

        return stringSize;
    }

The problem is that when I recall this function using something like

SizeF stringSize = new SizeF();
stringSize = MeasureStringMin(somestring, somefont, ????)

I never know what to put in the third variable, hints on this? Why do I need the PaintEventArgs?


Solution

  • You need the MeasureString function! Use it to get the exact dimensions of the string before you draw it, and adjust the position accordingly.