Практическое руководство. Создание частной коллекции шрифтов
Класс PrivateFontCollection наследуется от абстрактного базового класса FontCollection. Объект PrivateFontCollection можно использовать для поддержки набора шрифтов, собранного специально для приложения. Частная коллекция шрифтов может включать в себя как установленные системные шрифты, так и шрифты, которые не были установлены на компьютере. Чтобы добавить файл шрифта в частную коллекцию шрифтов, вызовите метод AddFontFile объекта PrivateFontCollection.
Свойство Families объекта PrivateFontCollection содержит массив объектов FontFamily.
Количество семейств шрифтов в частной коллекции шрифтов не обязательно должно совпадать с количеством файлов шрифтов, добавленных в коллекцию. Например, предположим, что в коллекцию были добавлены файлы ArialBd.tff, Times.tff и TimesBd.tff. В коллекции будет три файла, но только два семейства, так как Times.tff и TimesBd.tff принадлежат одному семейству.
Пример
В следующем примере в объект PrivateFontCollection добавляются следующие три файла шрифта:
C:\systemroot\Fonts\Arial.tff (Arial, обычный)
C:\systemroot\Fonts\CourBI.tff (Courier New, полужирный курсивный)
C:\systemroot\Fonts\TimesBd.tff (Times New Roman, полужирный)
Код извлекает массив объектов FontFamily из свойства Families объекта PrivateFontCollection.
Для каждого объекта FontFamily в коллекции код вызывает метод IsStyleAvailable, чтобы определить, доступны ли различные стили (обычный, полужирный, курсивный, полужирный курсивный, подчеркнутый или перечеркнутый). Аргументы, передаваемые методу IsStyleAvailable, являются членами перечисления FontStyle.
Если доступно определенное сочетание семейства и стиля, то с их помощью создается объект Font. Первым аргументом, передаваемым конструктору Font, является имя семейства шрифтов (а не объект FontFamily, как для других вариантов конструктора Font). После создания объекта Font он передается методу DrawString класса Graphics для отображения имени семейства и имени стиля.
Выходные данные следующего кода схожи с выходными данными, показанными на следующем рисунке:
Arial.tff (добавлен в коллекцию частных шрифтов в следующем примере кода) — это файл шрифта Arial обычного стиля. Обратите внимание, что в выходных данных программы отображаются несколько доступных стилей для семейства шрифтов Arial, помимо обычного. Это связано с тем, что GDI+ может имитировать полужирный, курсивный и полужирный курсив с использованием обычного стиля. GDI+ также может создавать из обычного стиля подчеркивание и перечеркивание.
Аналогичным образом, GDI+ может имитировать полужирный курсив из полужирного и курсивного стилей. Выходные данные программы показывают, что полужирный курсив доступен для семейства Times, несмотря на то, что TimesBd.tff (Times New Roman, полужирный) является единственным файлом Times в коллекции.
// Helper function to print text in a font and style
private float DrawFont(Graphics graphicsObj,
FontFamily family,
FontStyle style,
SolidBrush colorBrush,
PointF location,
string styleName)
{
// The string to print, which contains the family name and style
string familyNameAndStyle = $"{family.Name} {styleName}";
// Create the font object
using (Font fontObject = new Font(family.Name, 16, style, GraphicsUnit.Pixel))
{
// Draw the string
graphicsObj.DrawString(familyNameAndStyle, fontObject, colorBrush, location);
// Return the height of the font
return fontObject.Height;
}
}
// The OnPaint method of a form, which provides the graphics object
protected override void OnPaint(PaintEventArgs e)
{
PointF location = new PointF(10, 0);
SolidBrush solidBrush = new SolidBrush(Color.Black);
FontFamily[] fontFamilies;
PrivateFontCollection privateFontCollection = new PrivateFontCollection(); // Dispose later
// Add three font files to the private collection.
privateFontCollection.AddFontFile(System.Environment.ExpandEnvironmentVariables("%systemroot%\\Fonts\\Arial.ttf"));
privateFontCollection.AddFontFile(System.Environment.ExpandEnvironmentVariables("%systemroot%\\Fonts\\CourBI.ttf"));
privateFontCollection.AddFontFile(System.Environment.ExpandEnvironmentVariables("%systemroot%\\Fonts\\TimesBD.ttf"));
// Get the array of FontFamily objects.
fontFamilies = privateFontCollection.Families;
// Process each font in the collection
for (int i = 0; i < fontFamilies.Length; i++)
{
// Draw the font in every style
// Regular
if (fontFamilies[i].IsStyleAvailable(FontStyle.Regular))
location.Y += DrawFont(e.Graphics, fontFamilies[i], FontStyle.Regular, solidBrush, location, "Regular");
// Bold
if (fontFamilies[i].IsStyleAvailable(FontStyle.Bold))
location.Y += DrawFont(e.Graphics, fontFamilies[i], FontStyle.Bold, solidBrush, location, "Bold");
// Italic
if (fontFamilies[i].IsStyleAvailable(FontStyle.Italic))
location.Y += DrawFont(e.Graphics, fontFamilies[i], FontStyle.Italic, solidBrush, location, "Italic");
// Bold and Italic
if (fontFamilies[i].IsStyleAvailable(FontStyle.Bold) &&
fontFamilies[i].IsStyleAvailable(FontStyle.Italic))
location.Y += DrawFont(e.Graphics, fontFamilies[i], FontStyle.Bold | FontStyle.Italic, solidBrush, location, "BoldItalic");
// Underline
if (fontFamilies[i].IsStyleAvailable(FontStyle.Underline))
location.Y += DrawFont(e.Graphics, fontFamilies[i], FontStyle.Underline, solidBrush, location, "Underline");
// Strikeout
if (fontFamilies[i].IsStyleAvailable(FontStyle.Strikeout))
location.Y += DrawFont(e.Graphics, fontFamilies[i], FontStyle.Strikeout, solidBrush, location, "Strikeout");
// Extra space between font families
location.Y += 10;
}
privateFontCollection.Dispose();
}
' Helper function to print text in a font and style
Private Function DrawFont(graphicsObj As Graphics,
family As FontFamily,
style As FontStyle,
colorBrush As SolidBrush,
location As PointF,
styleName As String) As Single
' The string to print, which contains the family name and style
Dim familyNameAndStyle As String = $"{family.Name} {styleName}"
' Create the font object
Using fontObject As New Font(family.Name, 16, style, GraphicsUnit.Pixel)
' Draw the string
graphicsObj.DrawString(familyNameAndStyle, fontObject, colorBrush, location)
' Return the height of the font
Return fontObject.Height
End Using
End Function
' The OnPaint method of a form, which provides the graphics object
Protected Overrides Sub OnPaint(e As PaintEventArgs)
Dim location As New PointF(10, 0)
Dim solidBrush As New SolidBrush(Color.Black)
Dim fontFamilies() As FontFamily
Dim privateFontCollection As New PrivateFontCollection() ' Dispose later
' Add three font files to the private collection.
privateFontCollection.AddFontFile(System.Environment.ExpandEnvironmentVariables("%systemroot%\Fonts\Arial.ttf"))
privateFontCollection.AddFontFile(System.Environment.ExpandEnvironmentVariables("%systemroot%\Fonts\CourBI.ttf"))
privateFontCollection.AddFontFile(System.Environment.ExpandEnvironmentVariables("%systemroot%\Fonts\TimesBD.ttf"))
' Get the array of FontFamily objects.
fontFamilies = privateFontCollection.Families
' Process each font in the collection
For i = 0 To fontFamilies.Length - 1
' Draw the font in every style
' Regular
If fontFamilies(i).IsStyleAvailable(FontStyle.Regular) Then
location.Y += DrawFont(e.Graphics, fontFamilies(i), FontStyle.Regular, solidBrush, location, "Regular")
End If
' Bold
If fontFamilies(i).IsStyleAvailable(FontStyle.Bold) Then
location.Y += DrawFont(e.Graphics, fontFamilies(i), FontStyle.Bold, solidBrush, location, "Bold")
End If
' Italic
If fontFamilies(i).IsStyleAvailable(FontStyle.Italic) Then
location.Y += DrawFont(e.Graphics, fontFamilies(i), FontStyle.Italic, solidBrush, location, "Italic")
End If
' Bold and Italic
If fontFamilies(i).IsStyleAvailable(FontStyle.Italic) And
fontFamilies(i).IsStyleAvailable(FontStyle.Italic) Then
location.Y += DrawFont(e.Graphics, fontFamilies(i), FontStyle.Bold Or FontStyle.Italic, solidBrush, location, "BoldItalic")
End If
' Underline
If fontFamilies(i).IsStyleAvailable(FontStyle.Underline) Then
location.Y += DrawFont(e.Graphics, fontFamilies(i), FontStyle.Underline, solidBrush, location, "Underline")
End If
' Strikeout
If fontFamilies(i).IsStyleAvailable(FontStyle.Strikeout) Then
location.Y += DrawFont(e.Graphics, fontFamilies(i), FontStyle.Strikeout, solidBrush, location, "Strikeout")
End If
' Extra space between font families
location.Y += 10
Next
privateFontCollection.Dispose()
End Sub
Компиляция кода
Приведенный выше пример предназначен для использования с Windows Forms и требуется PaintEventArgse
, который является параметром PaintEventHandler.
См. также
.NET Desktop feedback