如何在Visual Basic .Net应用程序中嵌入字体?哪个应该适用于每个操作系统.
可以在应用程序中嵌入字体,如果该字体在用户系统上不可用,则可以使用它.
您只需创建一个PrivateFontCollection并使用您的字体填充它,然后您可以随意使用它们.根据MSDN,此方法不适用于Windows 2000之前的操作系统.
从PrivateFontCollection.AddFontFile方法的备注部分:
在Windows 2000之前在操作系统上使用私有字体时,将替换默认字体,通常为Microsoft Sans Serif.
如果您打算在Windows 2000及更高版本上使用您的应用程序,您可以按照我编写的代码来了解如何实现私有字体.
Public Class Form1
Dim pfc As System.Drawing.Text.PrivateFontCollection
Dim ifc As System.Drawing.Text.InstalledFontCollection
Sub New()
' This call is required by the designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
pfc = New System.Drawing.Text.PrivateFontCollection()
ifc = New System.Drawing.Text.InstalledFontCollection()
LoadPrivateFonts({My.Resources.Series_60_ZDigi, My.Resources.Times_NR_Phonetics_2})
End Sub
''' <summary>Loads the private fonts.</summary>
''' <param name="fonts">The fonts to be loaded into the private font collection.</param>
Private Sub LoadPrivateFonts(ByVal fonts As IEnumerable(Of Byte()))
For Each resFont In fonts
pfc.AddMemoryFont(Runtime.InteropServices.Marshal.UnsafeAddrOfPinnedArrayElement(resFont, 0), resFont.Length)
Next
End Sub
''' <summary>Gets the FontFamily whose name matches the one specified.</summary>
''' <param name="fontName">Name of the FontFamily to be returned.</param>
''' <param name="defaultFamily">
''' Optional. The default font family to be returned if the specified font is not found
''' </param>
Private Function GetFontFamily(ByVal fontName As String, Optional ByVal defaultFamily As FontFamily = Nothing) As FontFamily
If String.IsNullOrEmpty(fontName) Then
Throw New ArgumentNullException("fontName", "The name of the font cannont be null.")
End If
Dim foundFonts = From font In ifc.Families.Union(pfc.Families) Where font.Name.ToLower() = fontName.ToLower()
If foundFonts.Any() Then
Return foundFonts.First()
Else
Return If(defaultFamily, FontFamily.GenericSansSerif)
End If
End Function
Private Sub Form1_Disposed(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Disposed
'free the resources used by the font collections
pfc.Dispose()
ifc.Dispose()
End Sub
Private Sub Form1_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles Me.Paint
Dim g = e.Graphics
Using br As Brush = Brushes.Black
g.DrawString("1234567890ABCDEF", New Font(GetFontFamily("Series 60 ZDigi"), 18), br, New Point(20, 20))
g.DrawString("ABCDEFGHIJKLMNOP", New Font(GetFontFamily("Times NR Phonetics 2"), 18), br, New Point(20, 100))
End Using
End Sub
End Class
Run Code Online (Sandbox Code Playgroud)
我将我在应用程序中使用的两种字体(Series 60 ZDigi,我的诺基亚手机中的字体,以及Times NR Phonetics 2,我的字典应用程序中的字体)从资源加载到私有字体集合中Sub New().
然后,我调用该GetFontFamily方法以获取所需的字体以在表单上绘制.
将它合并到您的应用程序中应该不会太难.
干杯.
| 归档时间: |
|
| 查看次数: |
6756 次 |
| 最近记录: |