Загрузить шрифт из файла TTF | .NET

Здесь описаны четыре по-разному выполненных примера, как загрузить шрифт из файла Montserrat-Regular.ttf.


Сначала изучите основы загрузки на странице Как загрузить шрифты?.

Добавьте следующие пространства имен в начало файла:

1using System;
2using Aspose.Font;
3using Aspose.Font.Sources;
4using System.IO;

Загрузка из файла с использованием объекта FileSystemStreamSource

Для выполнения операции выполните следующие действия:

  1. Постройте путь к файлу.
  2. Инициализируйте объект FontDefiniton.
  3. Установите для fileExtension значение ttf.
  4. Загрузите шрифт.
 1    // Construct path to the file
 2    string fontPath = Path.Combine(DataDir, "Montserrat-Regular.ttf");
 3
 4    // Initialize FontDefinition object passing TTF as FontType value and using FontFileDefinition
 5    FontFileDefinition fileDef = new FontFileDefinition("ttf", new FileSystemStreamSource(fontPath));
 6
 7    // Based on FileSystemStreamSource object, set fileExtension to "ttf"
 8    FontDefinition fontDef = new FontDefinition(FontType.TTF, fileDef);
 9
10    // Load the font
11    Font font = Font.Open(fontDef);

Загрузка из файла с использованием объекта FileInfo

Для выполнения загрузки сделайте следующее:

  1. Постройте путь к файлу.
  2. Инициируйте объект FontDefiniton, передав TTF в качестве значения FontType.
  3. Получите автоматически рассчитанное значение fileExtension.
  4. Загрузите шрифт.
 1     // Construct path to the file
 2     string fontPath = Path.Combine(DataDir, "Montserrat-Regular.ttf");
 3
 4     // Initialize FontDefinition object passing TTF as FontType value and using FontFileDefinition
 5     FontFileDefinition fileDef = new FontFileDefinition(new FileInfo(fontPath));
 6
 7     // Based on FileInfo object, fileExtension value is calculated automatically from FileInfo fields.
 8     FontDefinition fontDef = new FontDefinition(FontType.TTF, fileDef);
 9
10     // Load the font
11     Font font = Font.Open(fontDef);

Загрузка из файла с исключением объекта FontFileDefinition из цепочки инициализации

Чтобы загрузить шрифт таким образом, необходимо выполнить следующие действия:

  1. Постройте путь к файлу.
  2. Инициируйте объект FontDefiniton, передав TTF как значение FontType, ttf как значение fileExtension и объект FileSystemStreamSource. . Параметр fileExtension здесь не является повторяющимся значением параметра FontType.
  3. Загрузите шрифт.
 1     // Construct path to the file
 2     string fontPath = Path.Combine(DataDir, "Montserrat-Regular.ttf");
 3
 4     // Initialize FontDefinition object passing TTF as FontType value, "ttf" as fileExtension value, 
 5     // and FileSystemStreamSource object. Parameter 'fileExtension' here is not duplicate value 
 6     // for parameter 'FontType' and it's needed for correct font format detection
 7     FontDefinition fontDef = new FontDefinition(FontType.TTF, "ttf", new FileSystemStreamSource(fontPath));
 8
 9     // Load the font
10     Font font = Font.Open(fontDef);     

Загрузка шрифта из байтового массива

Чтобы загрузить шрифт из массива байтов:

  1. Постройте путь к файлу.
  2. Загрузите двоичные данные шрифта в массив байтов.
  3. Инициализируйте объект FontDefiniton, передав TTF как значение FontType, ttf как значение fileExtension и ByteContentStreamSource. объект на основе массива fontBytes.
  4. Загрузите шрифт.
 1     // Construct path to the file
 2     string fontPath = Path.Combine(DataDir, "Montserrat-Regular.ttf");
 3
 4     // Load font binary data into byte array
 5     byte[] fontBytes = File.ReadAllBytes(fontPath);
 6
 7     // Initialize FontDefinition object  passing TTF as FontType value, "ttf" as fileExtension value, 
 8     // and ByteContentStreamSource object based on fontBytes array
 9     FontDefinition fontDef = new FontDefinition(FontType.TTF), "ttf", new ByteContentStreamSource(fontBytes);
10
11     // Load the font
12     Font font = Font.Open(fontDef);

You can get examples on how to use Aspose.Font in Aspose.Font.Examples.sln solution, in the net-examples of the Aspose.Font Documentation.

Subscribe to Aspose Product Updates

Get monthly newsletters & offers directly delivered to your mailbox.