1

I need to create bitmaps of characters depending on a specified font. When they specify a font, they are specifying:

  • Font (e.g. Microsoft Sans Serif)
  • Font style (e.g. Bold)
  • Size (e.g. 14)
  • Effects (e.g. Stikeout)
  • Script (e.g. Western)

Knowing this, is it possible to determine the size that a character will be exactly if I know the character and all the information above? I have to draw them to bitmaps that are the same size as the character and no bigger.

Thanks! I'm doing this all in VB.net so all .net examples are acceptable.

Freesnöw
  • 30,619
  • 30
  • 89
  • 138

1 Answers1

2

You need to use the Graphics.MeasureString() method. Create the graphics object for the form (or other graphics output object) and the font and use them to measure the text.

Public Sub Form1_Shown(sender As Object, e As EventArgs) Handles Me.Shown
    Using _
        graphics As Graphics = Me.CreateGraphics, _
        font As New Font("Microsoft Sans Serif", 14, FontStyle.Bold Or FontStyle.Strikeout)

        Dim text As String = "How big am I?"
        Dim size As SizeF = graphics.MeasureString(text, font)
        MessageBox.Show(size.ToString)
    End Using
End Sub
Hand-E-Food
  • 12,368
  • 8
  • 45
  • 80
  • 1
    You may wish to use TextRenderer.MeasureText() instead if you're not using the Graphics object to draw the text. – Chris Dunaway Sep 08 '11 at 14:24
  • @Chris: Thanks for that! I knew there had to be a better way. – Hand-E-Food Sep 08 '11 at 23:53
  • @Hand: I think Graphics.MeasureString is ok to use as well, but I think in the most recent versions of .Net, the TextRenderer is used to render text so MeasureText might be more appropriate. – Chris Dunaway Sep 09 '11 at 13:59