How to use MeasureString method?

1

I have the following code:

var font = new Font("Arial", 50);
var texto = "Meu texto";

var res = Graphics.MeasureString(texto, font); // Está linha não funciona.

When compiling the following error is generated:

  

An object reference is required for the non-static field,   method, or property 'System.Drawing.Graphics.MeasureString (string,   System.Drawing.Font) '

What do I need to do to use MeasureString ?

    
asked by anonymous 10.11.2015 / 18:14

2 answers

0

Just create the following method:

private float GetWidthOfString(string str, Font font, int bitmapWidth, int bitmapHeight)
    {
        Bitmap objBitmap = default(Bitmap);
        Graphics objGraphics = default(Graphics);

        objBitmap = new Bitmap(bitmapWidth, bitmapHeight);
        objGraphics = Graphics.FromImage(objBitmap);

        SizeF stringSize = objGraphics.MeasureString(str, font);

        objBitmap.Dispose();
        objGraphics.Dispose();
        return stringSize.Width;
    }

Source: link

    
10.11.2015 / 20:45
1

Valid only for Windows Forms

If your goal is to get a Size object with the size of your string , you can use the MeasureText method of the TextRenderer class in this way

var size = TextRenderer.MeasureText('Seu Texto Aqui', fonteDoTexto);
    
10.11.2015 / 18:23