Friday, October 24, 2008

Converting a TrueType Font Character into a Bitmap

Here is an excellent article on creating a bitmap from a TrueType Font Character. If you want to create a symbol selection dialog with a ListView, these routines can generate the Bitmap image for the listview items.

This article did more than I needed. I only wanted to create the images for a ListView for all of the characters in a TrueType font. I have boiled down the code from the above article to the following:

Private Sub UpdateSymbolList(fontName as String)


For i As Integer = 0 To 255

Dim bm As Bitmap = ConvertChar(fontName, i, Color.Blue, 32, 32, 20)
ImageList1.Images.Add(i.ToString, bm)


ListView1.LargeImageList = ImageList1
ListView1.SmallImageList = ImageList1

For i As Integer = 0 To 255
Dim lvi As New ListViewItem
lvi.Text = i.ToString
lvi.ImageKey = i.ToString

End Sub

Public Shared Function ConvertChar(ByVal fontName As String, _
ByVal charCode As Integer, _
ByVal color As Color, _
ByVal bitmapWidth As Integer, _
ByVal bitmapHeight As Integer, _
ByVal characterSize As Single) As Bitmap

Dim charToDraw As Char = Chr(charCode)
Dim bitmap As New Bitmap(bitmapWidth, bitmapHeight)
Dim g As Graphics = Graphics.FromImage(bitmap)
Dim fnt As Font = New Font(fontName, characterSize, FontStyle.Regular)
Dim textFormat As New StringFormat()

textFormat.Alignment = StringAlignment.Center
textFormat.LineAlignment = StringAlignment.Center

g.DrawString(charToDraw.ToString, fnt, New SolidBrush(color), New RectangleF(0, 1, bitmapWidth, bitmapHeight), textFormat)

g.DrawRectangle(New Pen(Drawing.Color.Black, 1), New Rectangle(0, 0, bitmapWidth - 1, bitmapHeight - 1))

Return bitmap

End Function

No comments: