#822 – Deciding which TextFormattingMode to Use

The TextOptions.TextFormattingMode property indicates whether fonts should be formatted using the standard WPF algorithm or the legacy GDI method for positioning the individual glyphs in the font.  The property can have one of the following values:

  • Ideal – Default value, formats text using the standard WPF method.  Glyph shapes are preserved, independent of their final position on the display
  • Display – Positions edges of glyphs on pixel boundaries.  Can result in clearer edges of text.

You should use the value of Ideal, except for the situations listed below.

Set TextFormattingMode to Display when all of the following is true:

  • The FontSize of the text is 14 or less  (small text)
  • Text is not being transformed (scaled, rotated, translated)
  • The exact shape of the glyphs is not critical (e.g. for some graphic design scenario)

#821 – Use TextFormattingMode to Make Text Look More Clear

WPF tries to retain the exact shape and style of each glyph in a font, no matter what size the font is being rendered at.  This means that as the text gets smaller, relative to the pixel density of the display, the edges of the glyphs may no longer occur at pixel boundaries.  When this happens, WPF will use anti-aliasing to render the edges of the glyphs in a different color.  This can lead to small text looking fuzzy, or having some odd color fragments along the edges of the letters.

To avoid fuzzy text at small sizes, you can set the TextOptions.TextFormattingMode property to Display (as opposed to the default value of Ideal).  This tells WPF to align the glyphs at pixel boundaries, which can lead to crisper/cleaner text.

        <TextBlock Text="WiWi WIWI HaHaHa (Ideal = Default)"
                   Margin="5"/>
        <TextBlock Text="WiWi WIWI HaHaHa (Display)"
                   TextOptions.TextFormattingMode="Display"
                   Margin="5"/>

821-001

#820 – Viewing Additional Font Properties in Windows Explorer

You can preview TrueType fonts in Windows Explorer and also get some basic properties about each font.  If you right-click on a font file, select Properties and then select the Details tab, you’ll see some basic information:

820-001

You can also download a Microsoft-provided tool, the OpenType Font File Properties Extension, to get even more information about each font.  You can download the tool from here.  (This tool will only work on 32-bit operating systems).

After installing the extension tool, the properties dialog for a font file will contain a number of additional tabs.

  • Embedding – Are you allowed to embed the font in your application?
  • CharSet/Unicode – What encoding method is used (e.g. Unicode)
  • Links – (optional) URL to font vendor
  • Description – General info on the font
  • License – license information
  • Version – font version
  • Hinting/Font Smoothing – point sizes for hinting/smoothing
  • Names – Font name, font family name, vendor, etc.
  • Features – Description from vendor

820-002

820-003

 

 

#819 – Previewing TrueType Fonts in Windows Explorer

You can view all installed fonts in Windows, using the Fonts applet.  You can also view font properties and preview arbitrary fonts using Windows Explorer.

For example, assume that you have a directory containing some TrueType (.ttf) fonts, which are not current installed.

You start by navigating to the folder containing the fonts.

819-001

You can set the view in Windows Explorer to one of the icon-based views (e.g. Large icons) to see a thumbnail-based preview of each font.

819-002

You can also turn on the Preview pane to see a preview of each font, as you select it.

819-003

Finally, as with the Fonts applet, you can double-click a font to open a preview of the font in a separate window.

819-004

#818 – Previewing Installed Fonts

You can easily get a preview of any of the fonts that are installed on your system.

You can see all installed fonts by opening the Fonts applet.  On Windows 8, click the Start button, type “fonts”, click on “Settings” in the search results and then double-click the Fonts icon.

818-001

 

This applet will show you a list of all fonts installed on your system, with each font displayed as a preview icon, or appearing as a stack of icons.

818-002

 

The icons that look like a stack indicate that there are multiple unique fonts for a particular font family.  Double-clicking on the stack shows you the individual fonts for that font family.

818-003

You can get a preview of any of the fonts by double-clicking the font (or right-clicking and selecting Preview).  A preview window will open, showing you a sample of the font.

818-004

 

#817 – Embedding a Font into Your Application

When you specify fonts that are to be used with your application, you typically specify font attributes, like FontFamily, and then let Windows look for a previously installed font that matches what you’re asking for.

If you have a non-standard font that you want to use and you have a copy of the TrueType (.ttf) file for the font, you can embed the font in your application, to make sure that your font gets used at run-time.

To embed a font, do the following:

Copy the font (.ttf file) into your project directory.  Add the font to your project by right-clicking on the project and selecting Add Existing Item.

817-001

Set the filter to All Files, find and select the .ttf file, and click Add.

817-002

817-003

Set the Build Action for the font to Resource.

817-004

Finally, set the FontFamily property to the font’s name, prefixing the name with “./#”.

817-004B

817-005

#816 – Using a Font Dialog to Select Fonts

Unlike Windows Forms, WPF does not include its own font selection dialog to allow users to pick fonts.  You can create your own dialog for this purpose, or you can use a font picker that someone else has developed.  (E.g. This one at Codeproject).

You can also just use the Windows Forms FontDialog class directly from WPF.

For example:

        <TextBlock Name="tbSomeText" Text="Little Lord Fauntleroy"
                   FontSize="16" Margin="10"/>
        <Button Content="Click to Choose" HorizontalAlignment="Center"
                Padding="10,5" Margin="10"
                Click="Button_Click"/>

In the code-behind, you use a FontDialog instance and then convert the selected font to the properties that you need in WPF.

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            FontDialog fd = new FontDialog();
            System.Windows.Forms.DialogResult dr = fd.ShowDialog();
            if (dr != System.Windows.Forms.DialogResult.Cancel)
            {
                tbSomeText.FontFamily = new System.Windows.Media.FontFamily(fd.Font.Name);
                tbSomeText.FontSize = fd.Font.Size * 96.0 / 72.0;
                tbSomeText.FontWeight = fd.Font.Bold ? FontWeights.Bold : FontWeights.Regular;
                tbSomeText.FontStyle = fd.Font.Italic ? FontStyles.Italic : FontStyles.Normal;
            }
        }

You’ll also need to add a reference to the System.Windows.Forms assembly.

816-001

 

816-002

 

816-003

 

816-004

#815 – Filling a ListBox with a List of All Fonts

The static Fonts.SystemFontFamilies property contains list of all fonts installed on your system.  Each element in the collection referenced by this property is a FontFamily object.

You can build a list of all fonts by binding a ListBox to this collection.  The example below uses a CollectionViewSource element, bound to SystemFontFamilies, which allows us to sort the items in the collection.  We then bind the ListBox to this collection.

<Window
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:scm="clr-namespace:System.ComponentModel;assembly=WindowsBase"
        x:Class="WpfApplication2.MainWindow"
        Width="300" Height="200"
        Title="Display a List of Fonts">

    <Window.Resources>
        <CollectionViewSource x:Key="allFonts"
                              Source="{Binding Source={x:Static Fonts.SystemFontFamilies}}">
            <CollectionViewSource.SortDescriptions>
                <scm:SortDescription PropertyName="Source"/>
            </CollectionViewSource.SortDescriptions>
        </CollectionViewSource>
    </Window.Resources>

    <Grid>
        <ListBox ItemsSource="{Binding Source={StaticResource allFonts}}"
                 Margin="5" ScrollViewer.VerticalScrollBarVisibility="Auto">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding}"
                               FontFamily="{Binding}"
                               FontSize="14"/>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
    </Grid>
</Window>

We display each item in the list using the appropriate font by using a data template and setting the FontFamily property of a TextBlock.

815-001

#814 – You Can Specify a List of Fonts to Try

You normally indicate the font or typeface to use in rendering a control by specifying a value for the FontFamily property.

        <TextBlock Padding="20,10" FontSize="16"
                   FontFamily="Corbel">
            I drank what?  --Socrates
        </TextBlock>

814-001
However, you can also supply a list of fonts for the FontFamily property.  WPF will attempt to use the first font listed, but if the font is not installed on the target system, it will fall back to the next font in the list.  This fallback mechanism will continue, as WPF tries each font in the list.  If none of the fonts listed are found, WPF will use the default font, Segoe UI.

        <TextBlock Padding="20,10" FontSize="16"
                   FontFamily="Baskerville,Georgia">
            I drank what?  --Socrates
        </TextBlock>

814-002

#337 – Specifying Font Properties for All Controls In a Window

Because the various font-related properties are dependency properties, they can be set on a high-level element in the logical tree and “trickle down” to lower-level elements.  The lower-level elements inherit property values from higher-level elements.

In the example below, we specify a font to use for all child controls within a window.

<Window
	xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
	xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
	xmlns:Microsoft_Windows_Themes="clr-namespace:Microsoft.Windows.Themes;assembly=PresentationFramework.Aero"
	x:Class="WpfApplication11.MainWindow"
	x:Name="Window"
	Title="Quotes"
	Width="780" Height="368"
    FontFamily="Georgia">

    <StackPanel>
        <Label Content="A nice quote:" Margin="20,10,20,0"/>

        <TextBlock Name="txt2" Margin="20" FontSize="18" TextWrapping="Wrap">
            Freedom is never dear at any price. It is the breath of life. What would a man not pay for living?<LineBreak/>
            --Mohandas Gandhi
        </TextBlock>

        <StackPanel Orientation="Horizontal" HorizontalAlignment="Center">
            <RadioButton Content="Like" Margin="10"/>
            <RadioButton Content="Don't Like" Margin="10"/>
        </StackPanel>

        <Button Content="OK" FontFamily="Tahoma" Width="100" Margin="20"/>
    </StackPanel>


Notice that we can override an inherited property by setting it explicitly for a control. We specify that Tahoma should be the FontFamily for the Button control.