How to use Measurestring method?

Asked

Viewed 166 times

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 needs to be done to use the MeasureString?

  • It is windows Forms?

  • Asp.Net MVC . Net Framework 4. Works will be?

  • 1

    No. I’ll see a solution for you. Don’t forget to tag asp.net mvc

2 answers

1

Solution valid only for Windows Forms

If your goal is to obtain an object Size the size of your string, you can use the method MeasureText class TextRenderer thus

var size = TextRenderer.MeasureText('Seu Texto Aqui', fonteDoTexto);

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: https://stackoverflow.com/a/12635970/4720858

Browser other questions tagged

You are not signed in. Login or sign up in order to post.