如何正确渲染嵌入式字体? [英] How to properly render an embedded Font?
问题描述
我下载了True Type字体,并将其嵌入为此页面进行了说明。
我必须设置 UseCompatibleTextRendering
属性才能加载它,但是看起来非常奇怪,我不知道为什么它在浏览器中看起来不错,但在应用程序中却看不出来。
I download a True Type Font and I embedded it just as this page explains.
I had to set the UseCompatibleTextRendering
property to be able to load it but it looks very weird, I don't know why it looks good in the browser but not in the application.
请注意,我将字体添加到了资源中,将其设置为嵌入式资源,我使用了这个模块:
Just to be clear I added the font to my resources, set it as embedded resource, I used this module:
Imports System.IO
Imports System.Reflection
Imports System.Drawing.Text
Imports System.Runtime.InteropServices
Module ExternalFontType
Public Function GetFont(aAssembly As Assembly,
strFontName As String, intFontSize As Integer,
fsFontStyle As FontStyle) As Font
Using pcolFonts As New PrivateFontCollection
Dim bFont() As Byte = ExternalFontType.bRawFontData(aAssembly, strFontName)
Dim ptrMemFont As IntPtr =
Marshal.AllocCoTaskMem(bFont.Length)
Marshal.Copy(bFont, 0, ptrMemFont, bFont.Length)
pcolFonts.AddMemoryFont(ptrMemFont, bFont.Length)
Marshal.FreeCoTaskMem(ptrMemFont)
Return New Font(pcolFonts.Families(0),
intFontSize, fsFontStyle)
End Using
End Function
Private Function bRawFontData(aAssembly As Assembly, strFontName As String) As Byte()
Using stFont As Stream =
aAssembly.GetManifestResourceStream(strFontName)
If (stFont Is Nothing) Then Throw _
New Exception(String.Format("Cannot load _
font '{0}'", strFontName))
Dim bFontBuffer() As Byte = New _
Byte(CInt(stFont.Length - 1)) {}
stFont.Read(bFontBuffer, 0, CInt(stFont.Length))
Return bFontBuffer
End Using
End Function
End Module
并将其包含在此代码中
lbl.UseCompatibleTextRendering = True
lbl.Font = ExternalFontType.GetFont(Me.GetType.Assembly, "ProyectName.FontName.ttf", 15, FontStyle.Bold)
推荐答案
该代码存在多个问题:
-
PrivateFontCollection 不能用
使用
声明:只要需要它指向的字体,就必须保留该集合。通常在使用它的类(Form)或共享类(或此处的Module)中将其声明为Field,然后在不再需要时进行处理。
The PrivateFontCollection cannot be declared with a
Using
statement: this collection must be preserved as long as the Fonts it points to are needed. It's usually declared as a Field in the class (Form) that uses it or in a shared class (or Module, here), then disposed of when not needed anymore.
Marshal.FreeCoTaskMem()
不能在这里使用;在 Marshal.AllocCoTaskMem()
之后调用它是一种诱惑,但在这种情况下则不行。这可以(将)损害字体数据的分配。您需要做的是处置 PrivateFontcollection
对象。该框架将处理COM 事务(即使您忘记处置 PrivateFontcollection $ c $,它也会为您执行此操作
Marshal.FreeCoTaskMem()
cannot be used here; it's a temptation to call it after Marshal.AllocCoTaskMem()
, but not in this occasion. This can (will) compromise the Font data allocation. What you need to do is dispose of the PrivateFontcollection
object. The Framework will take care of the COM affair (it will do it for you even if you forget to dispose of the PrivateFontcollection
object. It must not forget, though).
不需要汇编程序引用。所需的字体将以字节数组的形式添加到项目的资源中。然后可以通过名称(例如 My.Resources.SomeFontName
)或使用 ResourceManager.GetObject()方法,将返回的对象转换为 Byte()
:
The assembly reference is not needed. The Font is added to the Project's Resources as a byte array, which is all that's needed. It can than be retrieved either by name, e.g., My.Resources.SomeFontName
, or using the ResourceManager.GetObject() method, casting the returned object to Byte()
:
Dim fontData As Byte() = My.Resources.SomeFontName
Dim fontData As Byte() = DirectCast(My.Resources.ResourceManager.GetObject("SomeFontName"), Byte())
►您已经提到了这一点,但让我们再说一遍:并非所有控件都可以使用这些字体。只有可以使用GDI +绘制的字体的控件才能实际使用 PrivateFontCollection
中的字体,其中的Label和Button控件都在其中,实际上它们都公开了 UseCompatibleTextRendering 属性。
► You have already mentioned this but let's say it again: not all controls can use these Fonts. Only controls that can use Fonts drawn by GDI+ can actually use Fonts from the PrivateFontCollection
, the Label and Button controls are among of these, in fact both expose a UseCompatibleTextRendering property. A RichTextBox, for example, cannot.
Private myFontCollection As PrivateFontCollection = New PrivateFontCollection()
在窗体的构造函数中,从项目的资源中添加字体。
In the Form's Constructor, add Font from the Project's Resources.
-
此处我正在使用帮助器类
FontManager
,该类公开了公共共享
方法AddFontsFromResource()
:将PrivateFontCollection
以及与字体名称相对应的资源名称列表传递给此方法。 >
此方法将可以成功安装的字体填充到集合中,并返回已安装的字体数。
当然,您可以使用其他喜欢引用字体的方法。
Here I'm using a helper class,
FontManager
, which exposes apublic shared
methodAddFontsFromResource()
: pass to this method thePrivateFontCollection
and a list of resources names corresponding to the Font names.
This method fills the collection with Fonts that can be installed successfully and returns the number of Fonts installed.
Of course you use whatever other method you prefer to reference your Fonts.
注意。在示例中,三个字体资源被添加到集合中:
{ FontFamily1Regular, FontFamily1Italics, OtherFontFamily}
但两个属于同一个 FontFamily
,因此 PrivateFontCollection
仅包含两个元素,而不是三个。
Note. In the example, three Font resources are added to the collection:
{"FontFamily1Regular", "FontFamily1Italics", "OtherFontFamily"}
but two belong to the same FontFamily
, so the PrivateFontCollection
will contain just two elements, not three.
Public Sub New()
Dim installedFontsCount = FontManager.AddFontsFromResources(myFontCollection,
{"FontFamily1Regular", "FontFamily1Italics", "OtherFontFamily"})
' The Font can set here or anywhere else
someLabel.UseCompatibleTextRendering = True
someLabel.Font = New Font(myFontCollection.Families(0), 10.5F, FontStyle.Regular)
someButton.UseCompatibleTextRendering = True
someButton.Font = New Font(myFontCollection.Families(0), 10.5F, FontStyle.Italic)
End Sub
处理很重要 PrivateFontCollection
时,不再需要它:当初始化它的窗体关闭时或在应用程序关闭之前:
您还可以使用共享对象引用可以在项目中任何地方使用的 PrivateFontCollection
。在这种情况下,需要在应用程序关闭时处置该集合。
It's important to dispose of the PrivateFontCollection
when it's not needed anymore: when the Form that initialized it closes or before the Application closes:
You could also use a shared object to reference a PrivateFontCollection
that can be used anywhere in the Project. In this case the collection needs to be disposed of when the Application closes.
Private Sub Form1_FormClosed(sender As Object, e As FormClosedEventArgs) Handles MyBase.FormClosed
myFontCollection.Dispose()
End Sub
Helper class:
Helper class:
Imports System.Drawing.Text
Imports System.Runtime.InteropServices
Public Class FontManager
Public Shared Function AddFontsFromResources(fontCollection As PrivateFontCollection, fontNames As String()) As Integer
If fontNames.Length = 0 Then Return Nothing
Dim installedFontsCount = 0
For Each fontName As String In fontNames
Try
Dim fontData As Byte() = CType(My.Resources.ResourceManager.GetObject(fontName), Byte())
If fontData Is Nothing Then Throw New InvalidOperationException()
Dim data As IntPtr = Marshal.AllocCoTaskMem(fontData.Length)
Marshal.Copy(fontData, 0, data, fontData.Length)
fontCollection.AddMemoryFont(data, fontData.Length)
installedFontsCount += 1
Catch ex As Exception
' Placeholder: Notify User/Log/Whatever
Debug.Print($"Font installation failed for {fontName}")
End Try
Next
Return installedFontsCount
End Function
End Class
C#版本:
C# version:
using System.Drawing.Text;
using System.Runtime.InteropServices;
public static int AddFontsFromResources(PrivateFontCollection fontCollection, string[] fontNames)
{
int installedFontsCount = 0;
if (fontNames.Length == 0) return 0;
foreach (string fontName in fontNames) {
try {
byte[] fontData = (byte[])Properties.Resources.ResourceManager.GetObject(fontName);
var data = Marshal.AllocCoTaskMem(fontData.Length);
Marshal.Copy(fontData, 0, data, fontData.Length);
fontCollection.AddMemoryFont(data, fontData.Length);
installedFontsCount += 1;
}
catch (Exception) {
// Placeholder: Notify User/Log/Whatever
Console.WriteLine($"Font installation failed for {fontName}");
}
}
return installedFontsCount;
}
这篇关于如何正确渲染嵌入式字体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!