アプリケーションにフォントを埋め込む

2020-06-07

今回お借りしたフォント
源真ゴシック (げんしんゴシック) | 自家製フォント工房

プロジェクト

Fontフォルダを作成し、フォントファイルを格納
ビルドアクションはResource
(例としてFontフォルダにしている 他のフォルダ名でもOK)

App.xaml

<Application x:Class="WpfApp14.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:WpfApp14"
             StartupUri="MainWindow.xaml">
    <Application.Resources>

        <ResourceDictionary>
            <FontFamily x:Key="GenShinGothicHeavy">
                /WpfApp14;component/Font/GenShinGothic-Heavy.ttf#源真ゴシック Heavy
            </FontFamily>
        </ResourceDictionary>
        
    </Application.Resources>
</Application>

MainWindow.xaml

<Window x:Class="WpfApp14.MainWindow"
        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:local="clr-namespace:WpfApp14"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <StackPanel>
        <TextBlock Text="サンプル文字列" FontSize="20"/>
        <TextBlock Text="サンプル文字列" FontFamily="{StaticResource GenShinGothicHeavy}" FontSize="20" />
    </StackPanel>
</Window>

おまけ

文字の表示が汚い等の場合は、 TextOptions で調整するとよい
WPF のフォントは汚い?

C#,WPFC#,Font,WPF

Posted by とど