How To Read An Embedded Font File In Visual Basic

  • Thread starter Thread starter David William Smith
  • Start date Start date
D

David William Smith

Guest
I am working with the following code and get an exception error (Unable to Load Font dungeon.ttf)

I currently have the font file saved in a Resource and it's Properties Set To Embedded



Imports System.IO

Imports System.Reflection
Imports System.Drawing.Text
Imports System.Runtime.InteropServices

Module Embedded_Font
Public Function LoadFont(Asm As Assembly, Name As String, Size As Integer, Style As FontStyle) As Font
Using Collection As New PrivateFontCollection
Dim Bytes() As Byte = Embedded_Font.FontData(Asm, Name)
Dim Ptr As IntPtr = Marshal.AllocCoTaskMem(Bytes.Length)
Marshal.Copy(Bytes, 0, Ptr, Bytes.Length)
Collection.AddMemoryFont(Ptr, Bytes.Length)
Marshal.FreeCoTaskMem(Ptr)
Return New Font(Collection.Families(0), Size, Style)
End Using
End Function
Private Function FontData(Asm As Assembly, Name As String) As Byte()
Using Stream As Stream = Asm.GetManifestResourceStream(Name)
If (Stream Is Nothing) Then Throw New Exception(String.Format("Unable to load font '{0}'", Name))
Dim Buffer() As Byte = New Byte(CInt(Stream.Length - 1)) {}
Stream.Read(Buffer, 0, CInt(Stream.Length))
Return Buffer
End Using
End Function
End Module

Usage:

MyControl.Font = Embedded_Font.LoadFont(Me.GetType.Assembly, "dungeon.ttf", 9, FontStyle.Regular)

Any Recommendations to solve this problem

Continue reading...
 
Back
Top