1 Attachment(s)
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!
Re: Embedding and using custom fonts
Just asking, why not make it a little more friendly and add some properties and what not to make font selection easier, or make a full fledged manager maybe? Just a few thoughts, but nice little addition here.
Re: Embedding and using custom fonts
Properties? Like what? There's nothing you can change about a font file...
(I think I'm missing the point :p)
Re: Embedding and using custom fonts
I posted something similar to this the other day but that would let you use them from the project resources... check the "Using fonts in your project that are embedded in resources" in my sig!
Kris
Re: Embedding and using custom fonts
Quote:
Originally Posted by
minitech
Properties? Like what? There's nothing you can change about a font file...
(I think I'm missing the point :p)
You totally are, I'll have an update in the future :)
Re: Embedding and using custom fonts
@i00: This lets you use them from the project resources, did you look at the attachment?