Results 1 to 6 of 6

Thread: Embedding and using custom fonts

Threaded View

  1. #1

    Thread Starter
    Stack Overflow mod​erator
    Join Date
    May 2008
    Location
    British Columbia, Canada
    Posts
    2,824

    Talking Embedding and using custom fonts

    Here's a class that allows you to use custom fonts in your application. (I've also attached a demo that changes a label's font to a font I found on Google Webfonts.)

    Code:
    Imports System.Drawing
    Imports System.Drawing.Text
    Imports System.Runtime.InteropServices
    
    ''' <summary>
    ''' Represents a custom font not installed on the user's system.
    ''' </summary>
    Public NotInheritable Class CustomFont
        Implements IDisposable
    
        Private fontCollection As New PrivateFontCollection()
        Private fontPtr As IntPtr
    
    #Region "Constructor"
        ''' <summary>
        ''' Creates a new custom font using the specified font data.
        ''' </summary>
        ''' <param name="fontData">The font data representing the font.</param>
        Public Sub New(ByVal fontData() As Byte)
            'Create a pointer to the font data and copy the
            'font data into the location in memory pointed to
            fontPtr = Marshal.AllocHGlobal(fontData.Length)
            Marshal.Copy(fontData, 0, fontPtr, fontData.Length)
    
            'Add the font to the shared collection of fonts:
            fontCollection.AddMemoryFont(fontPtr, fontData.Length)
        End Sub
    #End Region
    
    #Region "Destructor"
        'Free the font in unmanaged memory, dispose of
        'the font collection and suppress finalization
        Public Sub Dispose() Implements IDisposable.Dispose
            Marshal.FreeHGlobal(fontPtr)
            fontCollection.Dispose()
    
            GC.SuppressFinalize(Me)
        End Sub
    
        'Free the font in unmanaged memory
        Protected Overrides Sub Finalize()
            Marshal.FreeHGlobal(fontPtr)
        End Sub
    #End Region
    
    #Region "Properties"
        ''' <summary>
        ''' Gets the font family of the custom font.
        ''' </summary>
        Public ReadOnly Property Font() As FontFamily
            Get
                Return fontCollection.Families(0)
            End Get
        End Property
    #End Region
    
    End Class
    Enjoy!
    Attached Files Attached Files

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width