在这个分步指南中,我们将解释如何在 C# 中获取字体度量。本教程提供了在 C# 中获取 Type1 字体度量的代码,但是 Aspose.Font for .NET,一个 C# 字体库可以帮助您从其他字体类型以及包括 TruType 和 OpenType 字体格式中读取 C# 中的字体度量。
在 C# 中获取字体度量的步骤
- 从 NuGet.org 安装 Aspose.Font for .NET 包
- 包括 Aspose.Font、Aspose.Font.Sources 和 Aspose.Font.Type1 命名空间
- 将许可证应用到 Aspose.Font for .NET 以避免评估水印
- 将输入的 Type1 字体加载到 FileSystemStreamSource 对象中
- 从流源创建一个 FontFileDefinition 对象
- 从文件定义创建一个 FontDefinition 对象
- 打开字体定义为 Type1Font 对象
- 现在,获取Type1字体的所有metrics属性
字体包含有助于描述字体内字形的度量信息。字体的这种度量信息有助于计算机学习如何在屏幕上绘制字符和句子。如果我们想通过 .NET 应用程序中的代码处理这些指标信息,这不是一件容易的事。然而,Aspose.Font for .NET 使用上面提到的几个步骤使整个过程变得非常简单和容易。
在 C# 中获取字体度量的代码
using System; | |
//Add reference to Aspose.Font for .NET API | |
//Use following namespaces to get font metrics | |
using Aspose.Font; | |
using Aspose.Font.Sources; | |
using Aspose.Font.Type1; | |
namespace GetFontMetrics | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
//Set Aspose license before getting font metrics | |
//using Aspose.Font for .NET | |
Aspose.Font.License AsposeFontLicense = new Aspose.Font.License(); | |
AsposeFontLicense.SetLicense(@"c:\asposelicense\license.lic"); | |
//Load Type1 font into a file stream object & read font definition | |
FileSystemStreamSource Type1FontFileSource = new FileSystemStreamSource("SampleInputType1Font.pfb"); | |
FontFileDefinition Type1FontFileDefintion = new FontFileDefinition(Type1FontFileSource); | |
FontDefinition Type1FontDefinition = new FontDefinition(FontType.Type1, Type1FontFileDefintion); | |
//Open Type1 font | |
Type1Font InputType1Font = Font.Open(Type1FontDefinition) as Type1Font; | |
//Read font metrics information and use it for further processing | |
string FontName = InputType1Font.FontName; | |
int FontGlyphcount = InputType1Font.NumGlyphs; | |
double FontMetricsAscender = InputType1Font.Metrics.Ascender; | |
double FontMetricsDescender = InputType1Font.Metrics.Descender; | |
double FontMetricsTypoAscender = InputType1Font.Metrics.TypoAscender; | |
double FontMetricsTypoDescender = InputType1Font.Metrics.TypoDescender; | |
double FontMetricsUnitsPerEM = InputType1Font.Metrics.UnitsPerEM; | |
//display information to console in this case | |
Console.WriteLine( | |
"Font Name: {0}, " + | |
"Glyph Count: {1}, " + | |
"Asender: {2}, " + | |
"Descender: {3}, " + | |
"Typo Ascender: {4}, " + | |
"Typo Descender: {5}, " + | |
"Units Per EM: {6}", | |
FontName, | |
FontGlyphcount, | |
FontMetricsAscender, | |
FontMetricsDescender, | |
FontMetricsTypoAscender, | |
FontMetricsTypoDescender, | |
FontMetricsUnitsPerEM | |
); | |
} | |
} | |
} |
在上面的代码中,我们正在加载一个 PFB 文件格式,其中包含我们有兴趣在 C# 代码中处理的 Type1 字体。一旦我们加载了 font 并将其转换为 Type1Font 对象,我们就可以从该文件中提取 C# 中的字体规格。
此代码可以帮助您在 .NET 应用程序(包括 Web、桌面、Windows 和 Microsoft Store 应用程序)中轻松创建 C# 字体阅读器。