views:

357

answers:

2

I'm creating a custom control, part of which is using the Graphics class to draw text to the form. Currently I'm using the following code to display it:

private float _lineHeight { get { return this.Font.Size + 5; } }
private void Control_Paint(object sender, PaintEventArgs e)
{
    Graphics g = this.CreateGraphics();
    Brush b = new SolidBrush(Colors[7]);

    g.DrawString("Hello World!", this.Font, b, 0, 2);
    g.DrawString("This has been a test of the emergency drawing system!",
        this.Font, b, 0, 2 + _lineHeight);
}

I'm currently using fixedwidth fonts, and I'd like to know how wide the font will display, but there doesn't appear to be any properties for this sort of information. Is there some way of obtaining it? I want it so I can wrap lines properly when displayed.

+8  A: 

Yes, you can use MeasureString from the Graphics class

This method returns a SizeF structure that represents the size, in the units specified by the PageUnit property, of the string specified by the text parameter as drawn with the font parameter.

private void MeasureStringMin(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);

    // Draw rectangle representing size of string.
    e.Graphics.DrawRectangle(new Pen(Color.Red, 1), 0.0F, 0.0F, stringSize.Width, stringSize.Height);

    // Draw string to screen.
    e.Graphics.DrawString(measureString, stringFont, Brushes.Black, new PointF(0, 0));
}
Juan Manuel
Ah, in the Graphics class... Good call, I was looking high and low in the Font class for something.
Matthew Scharley
A: 
Size sizeOfText = TextRenderer.MeasureText("Hello World!", this.Font);

sizeofText now contains the size.

Hasan Khan