Como criar uma coleção de fontes privada

A PrivateFontCollection classe herda da FontCollection classe base abstrata. Você pode usar um objeto para manter um PrivateFontCollection conjunto de fontes especificamente para seu aplicativo. Uma coleção de fontes privada pode incluir fontes do sistema instalado, bem como as fontes que não foram instaladas no computador. Para adicionar um arquivo de fonte a uma coleção particular de fontes, chame o AddFontFile método de um PrivateFontCollection objeto.

A Families propriedade de um PrivateFontCollection objeto contém uma matriz de FontFamily objetos.

A quantidade de famílias de fonte em uma coleção de fontes privada não é necessariamente a mesma que a quantidade de arquivos de fonte que foram adicionados à coleção. Por exemplo, suponha que os arquivos ArialBd.tff, Times.tff e TimesBd.tff foram adicionados a uma coleção. Haverá três arquivos, mas somente duas famílias na coleção, pois Times.tff e TimesBd.tff pertencem à mesma família.

Exemplo

O exemplo a seguir adiciona os três arquivos de fonte a seguir a um PrivateFontCollection objeto:

  • C:\systemroot\Fonts\Arial.tff (Arial, regular)

  • C:\systemroot\Fonts\CourBI.tff (Courier New, negrito itálico)

  • C:\systemroot\Fonts\TimesBd.tff (Times New Roman, negrito)

O código recupera uma matriz de FontFamily objetos da Families propriedade do PrivateFontCollection objeto.

Para cada FontFamily objeto na coleção, o código chama o IsStyleAvailable método para determinar se vários estilos (regular, negrito, itálico, negrito itálico, sublinhado e tachado) estão disponíveis. Os argumentos passados para o IsStyleAvailable método são membros da FontStyle enumeração.

Se uma determinada combinação de família/estilo estiver disponível, um Font objeto será construído usando essa família e estilo. O primeiro argumento passado para o construtor é o nome da família da fonte (não um FontFamily objeto como é o Font caso de outras variações do Font construtor). Depois que o objeto é construído, ele é passado para o método da classe para exibir o Font nome da família junto com o DrawStringGraphics nome do estilo.

A saída do código a seguir é semelhante à saída mostrada na ilustração a seguir:

Screenshot that shows text in various fonts.

Arial.tff (adicionada à coleção de fontes privadas no exemplo de código a seguir) é o arquivo de fonte do estilo regular da fonte Arial. No entanto, observe que a saída de programa mostra vários estilos disponíveis além de regular para família de fonte Arial. Isso ocorre porque o GDI+ pode simular os estilos negrito, itálico e itálico negrito do estilo regular. GDI+ também pode produzir sublinhados e strikeouts do estilo regular.

Da mesma forma, o GDI+ pode simular o estilo itálico em negrito a partir do estilo negrito ou do estilo itálico. A saída do programa mostra que o estilo negrito e itálico está disponível para a família Times, embora TimesBd.tff (Times New Roman, negrito) seja o único arquivo Times na coleção.

PointF pointF = new PointF(10, 0);
SolidBrush solidBrush = new SolidBrush(Color.Black);

int count = 0;
string familyName = "";
string familyNameAndStyle;
FontFamily[] fontFamilies;
PrivateFontCollection privateFontCollection = new PrivateFontCollection();

// Add three font files to the private collection.
privateFontCollection.AddFontFile("D:\\systemroot\\Fonts\\Arial.ttf");
privateFontCollection.AddFontFile("D:\\systemroot\\Fonts\\CourBI.ttf");
privateFontCollection.AddFontFile("D:\\systemroot\\Fonts\\TimesBD.ttf");

// Get the array of FontFamily objects.
fontFamilies = privateFontCollection.Families;

// How many objects in the fontFamilies array?
count = fontFamilies.Length;

// Display the name of each font family in the private collection
// along with the available styles for that font family.
for (int j = 0; j < count; ++j)
{
    // Get the font family name.
    familyName = fontFamilies[j].Name;

    // Is the regular style available?
    if (fontFamilies[j].IsStyleAvailable(FontStyle.Regular))
    {
        familyNameAndStyle = "";
        familyNameAndStyle = familyNameAndStyle + familyName;
        familyNameAndStyle = familyNameAndStyle + " Regular";

        Font regFont = new Font(
           familyName,
           16,
           FontStyle.Regular,
           GraphicsUnit.Pixel);

        e.Graphics.DrawString(
           familyNameAndStyle,
           regFont,
           solidBrush,
           pointF);

        pointF.Y += regFont.Height;
    }

    // Is the bold style available?
    if (fontFamilies[j].IsStyleAvailable(FontStyle.Bold))
    {
        familyNameAndStyle = "";
        familyNameAndStyle = familyNameAndStyle + familyName;
        familyNameAndStyle = familyNameAndStyle + " Bold";

        Font boldFont = new Font(
           familyName,
           16,
           FontStyle.Bold,
           GraphicsUnit.Pixel);

        e.Graphics.DrawString(familyNameAndStyle, boldFont, solidBrush, pointF);

        pointF.Y += boldFont.Height;
    }
    // Is the italic style available?
    if (fontFamilies[j].IsStyleAvailable(FontStyle.Italic))
    {
        familyNameAndStyle = "";
        familyNameAndStyle = familyNameAndStyle + familyName;
        familyNameAndStyle = familyNameAndStyle + " Italic";

        Font italicFont = new Font(
           familyName,
           16,
           FontStyle.Italic,
           GraphicsUnit.Pixel);

        e.Graphics.DrawString(
           familyNameAndStyle,
           italicFont,
           solidBrush,
           pointF);

        pointF.Y += italicFont.Height;
    }

    // Is the bold italic style available?
    if (fontFamilies[j].IsStyleAvailable(FontStyle.Italic) &&
    fontFamilies[j].IsStyleAvailable(FontStyle.Bold))
    {
        familyNameAndStyle = "";
        familyNameAndStyle = familyNameAndStyle + familyName;
        familyNameAndStyle = familyNameAndStyle + "BoldItalic";

        Font italicFont = new Font(
           familyName,
           16,
           FontStyle.Italic | FontStyle.Bold,
           GraphicsUnit.Pixel);

        e.Graphics.DrawString(
           familyNameAndStyle,
           italicFont,
           solidBrush,
           pointF);

        pointF.Y += italicFont.Height;
    }
    // Is the underline style available?
    if (fontFamilies[j].IsStyleAvailable(FontStyle.Underline))
    {
        familyNameAndStyle = "";
        familyNameAndStyle = familyNameAndStyle + familyName;
        familyNameAndStyle = familyNameAndStyle + " Underline";

        Font underlineFont = new Font(
           familyName,
           16,
           FontStyle.Underline,
           GraphicsUnit.Pixel);

        e.Graphics.DrawString(
           familyNameAndStyle,
           underlineFont,
           solidBrush,
           pointF);

        pointF.Y += underlineFont.Height;
    }

    // Is the strikeout style available?
    if (fontFamilies[j].IsStyleAvailable(FontStyle.Strikeout))
    {
        familyNameAndStyle = "";
        familyNameAndStyle = familyNameAndStyle + familyName;
        familyNameAndStyle = familyNameAndStyle + " Strikeout";

        Font strikeFont = new Font(
           familyName,
           16,
           FontStyle.Strikeout,
           GraphicsUnit.Pixel);

        e.Graphics.DrawString(
           familyNameAndStyle,
           strikeFont,
           solidBrush,
           pointF);

        pointF.Y += strikeFont.Height;
    }

    // Separate the families with white space.
    pointF.Y += 10;
} // for
Dim pointF As New PointF(10, 0)
Dim solidBrush As New SolidBrush(Color.Black)

Dim count As Integer = 0
Dim familyName As String = ""
Dim familyNameAndStyle As String
Dim fontFamilies() As FontFamily
Dim privateFontCollection As New PrivateFontCollection()

' Add three font files to the private collection.
privateFontCollection.AddFontFile("D:\systemroot\Fonts\Arial.ttf")
privateFontCollection.AddFontFile("D:\systemroot\Fonts\CourBI.ttf")
privateFontCollection.AddFontFile("D:\systemroot\Fonts\TimesBD.ttf")

' Get the array of FontFamily objects.
fontFamilies = privateFontCollection.Families

' How many objects in the fontFamilies array?
count = fontFamilies.Length

' Display the name of each font family in the private collection
' along with the available styles for that font family.
Dim j As Integer

While j < count
    ' Get the font family name.
    familyName = fontFamilies(j).Name

    ' Is the regular style available?
    If fontFamilies(j).IsStyleAvailable(FontStyle.Regular) Then
        familyNameAndStyle = ""
        familyNameAndStyle = familyNameAndStyle & familyName
        familyNameAndStyle = familyNameAndStyle & " Regular"

        Dim regFont As New Font( _
           familyName, _
           16, _
           FontStyle.Regular, _
           GraphicsUnit.Pixel)

        e.Graphics.DrawString( _
           familyNameAndStyle, _
           regFont, _
           solidBrush, _
           pointF)

        pointF.Y += regFont.Height
    End If

    ' Is the bold style available?
    If fontFamilies(j).IsStyleAvailable(FontStyle.Bold) Then
        familyNameAndStyle = ""
        familyNameAndStyle = familyNameAndStyle & familyName
        familyNameAndStyle = familyNameAndStyle & " Bold"

        Dim boldFont As New Font( _
           familyName, _
           16, _
           FontStyle.Bold, _
           GraphicsUnit.Pixel)

        e.Graphics.DrawString( _
           familyNameAndStyle, _
           boldFont, _
           solidBrush, _
           pointF)

        pointF.Y += boldFont.Height
    End If

    ' Is the italic style available?
    If fontFamilies(j).IsStyleAvailable(FontStyle.Italic) Then
        familyNameAndStyle = ""
        familyNameAndStyle = familyNameAndStyle & familyName
        familyNameAndStyle = familyNameAndStyle & " Italic"

        Dim italicFont As New Font( _
           familyName, _
           16, _
           FontStyle.Italic, _
           GraphicsUnit.Pixel)

        e.Graphics.DrawString( _
           familyNameAndStyle, _
           italicFont, _
           solidBrush, pointF)

        pointF.Y += italicFont.Height
    End If

    ' Is the bold italic style available?
    If fontFamilies(j).IsStyleAvailable(FontStyle.Italic) And _
       fontFamilies(j).IsStyleAvailable(FontStyle.Bold) Then
        familyNameAndStyle = ""
        familyNameAndStyle = familyNameAndStyle & familyName
        familyNameAndStyle = familyNameAndStyle & "BoldItalic"

        Dim italicFont As New Font( _
            familyName, _
            16, _
            FontStyle.Italic Or FontStyle.Bold, _
            GraphicsUnit.Pixel)

        e.Graphics.DrawString( _
           familyNameAndStyle, _
           italicFont, _
           solidBrush, _
           pointF)

        pointF.Y += italicFont.Height
    End If
    ' Is the underline style available?
    If fontFamilies(j).IsStyleAvailable(FontStyle.Underline) Then
        familyNameAndStyle = ""
        familyNameAndStyle = familyNameAndStyle & familyName
        familyNameAndStyle = familyNameAndStyle & " Underline"

        Dim underlineFont As New Font( _
           familyName, _
           16, _
           FontStyle.Underline, _
           GraphicsUnit.Pixel)

        e.Graphics.DrawString( _
           familyNameAndStyle, _
           underlineFont, _
           solidBrush, _
           pointF)

        pointF.Y += underlineFont.Height
    End If

    ' Is the strikeout style available?
    If fontFamilies(j).IsStyleAvailable(FontStyle.Strikeout) Then
        familyNameAndStyle = ""
        familyNameAndStyle = familyNameAndStyle & familyName
        familyNameAndStyle = familyNameAndStyle & " Strikeout"

        Dim strikeFont As New Font( _
           familyName, _
           16, _
           FontStyle.Strikeout, _
           GraphicsUnit.Pixel)

        e.Graphics.DrawString( _
           familyNameAndStyle, _
           strikeFont, _
           solidBrush, _
           pointF)

        pointF.Y += strikeFont.Height
    End If

    ' Separate the families with white space.
    pointF.Y += 10
End While

Compilando o código

O exemplo anterior foi projetado para uso com o Windows Forms e requer PaintEventArgse, que é um parâmetro de PaintEventHandler.

Confira também