書式設定されたテキストの描画

ここでは、FormattedText オブジェクトの機能の概要について説明します。 このオブジェクトからは、Windows Presentation Foundation (WPF) アプリケーションでのテキストの描画に対する低レベルの制御が提供されます。

テクノロジの概要

FormattedText オブジェクトを使用すると、複数行のテキストを描画できます。このテキストでは、テキスト内の各文字を個々に書式設定できます。 複数の書式が適用されたテキストを次の例に示します。

Text displayed using FormattedText object

Note

Win32 API から移行する開発者のために、「Win32 の移行」の表に Win32 DrawText フラグと Windows Presentation Foundation (WPF) におけるほぼ同等のものを示します。

書式設定されたテキストを使用する理由

WPF には画面にテキストを描画するための複数のコントロールが含まれています。 各コントロールは異なるシナリオを対象にしており、それぞれに一連の機能と制限があります。 一般的に、ユーザー インターフェイス (UI) で短い文を使用するなど、限定的なテキストのサポートが必要な場合は、TextBlock 要素を使用する必要があります。 最小限のテキスト サポートが必要な場合は、Label を使用できます。 詳細については、「WPF のドキュメント」を参照してください。

FormattedText オブジェクトは、Windows Presentation Foundation (WPF) テキスト コントロールより強力なテキスト書式設定機能を備えており、テキストを装飾的要素として使用する場合に役立ちます。 詳細については、後の「書式設定されたテキストのジオメトリへの変換」を参照してください。

また、FormattedText オブジェクトは、テキスト指向の DrawingVisual 派生オブジェクトを作成する場合に役立ちます。 DrawingVisual は、図形、イメージ、またはテキストのレンダリングに使用する軽量の描画クラスです。 詳細については、「DrawingVisuals を使用したヒット テストのサンプル」を参照してください。

FormattedText オブジェクトの使用

書式設定されたテキストを作成するには、FormattedText コンストラクターを呼び出して FormattedText オブジェクトを作成します。 最初の書式設定済みテキスト文字列を作成したら、書式スタイルの範囲を適用できます。

テキストを特定の幅に制限するには、MaxTextWidth プロパティを使用します。 テキストは、指定された幅を超えないように自動的に折り返されます。 テキストを特定の高さに制限するには、MaxTextHeight プロパティを使用します。 テキストは、指定された高さを超えた部分に省略記号 "…" を表示します。

Text displayed with wordwrap and ellipsis.

複数の書式スタイルを 1 つ以上の文字に適用できます。 たとえば、SetFontSize メソッドと SetForegroundBrush メソッドの両方を呼び出して、テキストの最初の 5 文字の書式設定を変更できます。

FormattedText オブジェクトを作成し、複数の書式設定スタイルをテキストに適用するコード例を次に示します。

protected override void OnRender(DrawingContext drawingContext)
{
    string testString = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor";

    // Create the initial formatted text string.
    FormattedText formattedText = new FormattedText(
        testString,
        CultureInfo.GetCultureInfo("en-us"),
        FlowDirection.LeftToRight,
        new Typeface("Verdana"),
        32,
        Brushes.Black);

    // Set a maximum width and height. If the text overflows these values, an ellipsis "..." appears.
    formattedText.MaxTextWidth = 300;
    formattedText.MaxTextHeight = 240;

    // Use a larger font size beginning at the first (zero-based) character and continuing for 5 characters.
    // The font size is calculated in terms of points -- not as device-independent pixels.
    formattedText.SetFontSize(36 * (96.0 / 72.0), 0, 5);

    // Use a Bold font weight beginning at the 6th character and continuing for 11 characters.
    formattedText.SetFontWeight(FontWeights.Bold, 6, 11);

    // Use a linear gradient brush beginning at the 6th character and continuing for 11 characters.
    formattedText.SetForegroundBrush(
                            new LinearGradientBrush(
                            Colors.Orange,
                            Colors.Teal,
                            90.0),
                            6, 11);

    // Use an Italic font style beginning at the 28th character and continuing for 28 characters.
    formattedText.SetFontStyle(FontStyles.Italic, 28, 28);

    // Draw the formatted text string to the DrawingContext of the control.
    drawingContext.DrawText(formattedText, new Point(10, 0));
}
Protected Overrides Sub OnRender(ByVal drawingContext As DrawingContext)
    Dim testString As String = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor"

    ' Create the initial formatted text string.
    Dim formattedText As New FormattedText(testString, CultureInfo.GetCultureInfo("en-us"), FlowDirection.LeftToRight, New Typeface("Verdana"), 32, Brushes.Black)

    ' Set a maximum width and height. If the text overflows these values, an ellipsis "..." appears.
    formattedText.MaxTextWidth = 300
    formattedText.MaxTextHeight = 240

    ' Use a larger font size beginning at the first (zero-based) character and continuing for 5 characters.
    ' The font size is calculated in terms of points -- not as device-independent pixels.
    formattedText.SetFontSize(36 * (96.0 / 72.0), 0, 5)

    ' Use a Bold font weight beginning at the 6th character and continuing for 11 characters.
    formattedText.SetFontWeight(FontWeights.Bold, 6, 11)

    ' Use a linear gradient brush beginning at the 6th character and continuing for 11 characters.
    formattedText.SetForegroundBrush(New LinearGradientBrush(Colors.Orange, Colors.Teal, 90.0), 6, 11)

    ' Use an Italic font style beginning at the 28th character and continuing for 28 characters.
    formattedText.SetFontStyle(FontStyles.Italic, 28, 28)

    ' Draw the formatted text string to the DrawingContext of the control.
    drawingContext.DrawText(formattedText, New Point(10, 0))
End Sub

フォント サイズの単位

Windows Presentation Foundation (WPF) アプリケーションの他のテキスト オブジェクトと同様に、FormattedText オブジェクトでは、単位としてデバイス非依存ピクセルが使用されます。 ただし、ほとんどの Win32 アプリケーションでは、単位としてポイントが使用されます。 Windows Presentation Foundation (WPF) アプリケーションでポイント単位の表示テキストを使用する場合は、デバイスに依存しない単位 (1 単位は 1/96 インチ) をポイントに変換する必要があります。 この変換を実行する方法を次のコード例に示します。

// The font size is calculated in terms of points -- not as device-independent pixels.
formattedText.SetFontSize(36 * (96.0 / 72.0), 0, 5);
' The font size is calculated in terms of points -- not as device-independent pixels.
formattedText.SetFontSize(36 * (96.0 / 72.0), 0, 5)

書式設定されたテキストのジオメトリへの変換

書式設定したテキストを Geometry オブジェクトに変換し、人の目をひきつける他の種類のテキストを作成できます。 たとえば、テキスト文字列のアウトラインに基づいて Geometry オブジェクトを作成できます。

Text outline using a linear gradient brush

変換されたテキストのストローク、塗りつぶし、強調表示を変更して、人の目をひく視覚効果を作成するいくつかの方法を次の例に示します。

Text with different colors for fill and stroke

Text with image brush applied to stroke

Text with image brush applied to stroke and highlight

テキストを Geometry オブジェクトに変換すると、テキストは文字の集まりではなくなります。つまり、文字列内の文字を変更することはできません。 ただし、変換されたテキストのストロークおよび塗りつぶしのプロパティを変更することで、テキストの外観を変えることができます。 ストロークは、変換したテキストのアウトラインを参照します。塗りつぶしは、変換したテキストのアウトラインの内側の領域を参照します。 詳細については、「方法: 中抜きの文字列を作成する」を参照してください。

書式設定されたテキストを PathGeometry オブジェクトに変換し、そのオブジェクトをテキストの強調表示に使用することもできます。 たとえば、PathGeometry オブジェクトに 1 つのアニメーションを適用することができ、これによりアニメーションは書式設定されたテキストのアウトラインに従うようになります。

次の例では、PathGeometry オブジェクトに変換された書式付きテキストを示します。 アニメーション化された楕円は、レンダリングされたテキストのストロークのパスに従います。

Sphere following the path geometry of text
テキストのパス ジオメトリに続く球

詳細については、「方法: テキストの PathGeometry アニメーションを作成する」を参照してください。

書式設定したテキストを PathGeometry オブジェクトに変換したら、他の有意義な効果を作成することができます。 たとえば、ビデオをクリップしてテキスト内に表示することができます。

Video displaying in the path geometry of text

Win32 の移行

テキストを描画するための FormattedText の機能は、Win32 DrawText 関数の機能に似ています。 Win32 API から移行する開発者のために、Win32 DrawText フラグと Windows Presentation Foundation (WPF) におけるほぼ同等のものを次の表に示します。

DrawText フラグ 同等の WPF 操作 メモ
DT_BOTTOM Height 適切な Win32 DrawText の "y" 位置を計算するには、Height プロパティを使用します。
DT_CALCRECT HeightWidth 出力四角形を計算するには、Height プロパティと Width プロパティを使用します。
DT_CENTER TextAlignment TextAlignment プロパティを使用して値を Center に設定します。
DT_EDITCONTROL None 不要。 スペースの幅および最後の行のレンダリングは、フレームワークのエディット コントロールと同じです。
DT_END_ELLIPSIS Trimming Trimming プロパティを使用して値を CharacterEllipsis にします。

WordEllipsis を使用して、DT_WORD_ELIPSIS の末尾の省略記号が設定された Win32 DT_END_ELLIPSIS を取得します。この場合、省略記号は 1 行に収まらない単語にのみ表示されます。
DT_EXPAND_TABS None 不要。 タブは自動的に全角 4 文字分ごとに展開されます。これは、言語非依存文字の約 8 文字分の幅です。
DT_EXTERNALLEADING None 不要。 外部レディングは、常に行間隔に含まれます。 LineHeight プロパティを使用して、ユーザー定義の行間隔を作成します。
DT_HIDEPREFIX None サポートされていません。 FormattedText オブジェクトを構築する前に、文字列から "&" を削除します。
DT_LEFT TextAlignment これは、テキストの配置の既定値です。 TextAlignment プロパティを使用して値を Left に設定します。 (WPF のみ)。
DT_MODIFYSTRING None サポートされていません。
DT_NOCLIP VisualClip クリッピングは自動的には行われません。 テキストをクリップする場合は、VisualClip プロパティを使用します。
DT_NOFULLWIDTHCHARBREAK None サポートされていません。
DT_NOPREFIX None 不要。 文字列内の '&' 文字は、常に通常の文字として扱われます。
DT_PATHELLIPSIS None Trimming プロパティを使用して値を WordEllipsis にします。
DT_PREFIX None サポートされていません。 アクセラレータ キーやリンクなどのテキストにアンダースコアを使用する場合は、SetTextDecorations メソッドを使用します。
DT_PREFIXONLY None サポートされていません。
DT_RIGHT TextAlignment TextAlignment プロパティを使用して値を Right に設定します。 (WPF のみ)。
DT_RTLREADING FlowDirection FlowDirection プロパティを RightToLeftに設定します。
DT_SINGLELINE None 不要。 MaxTextWidth プロパティが設定されていない場合、またはテキストに改行コード (CR/LF) が含まれていない場合、FormattedText オブジェクトは単一行コントロールとして動作します。
DT_TABSTOP None ユーザー定義のタブ位置はサポートされていません。
DT_TOP Height 不要。 上端揃えが既定値です。 その他の垂直方向の配置の値を定義するには、Height プロパティを使用して、適切な Win32 DrawText の "y" 位置を計算します。
DT_VCENTER Height 適切な Win32 DrawText の "y" 位置を計算するには、Height プロパティを使用します。
DT_WORDBREAK None 不要。 単語の区切りは、FormattedText オブジェクトで自動的に行われます。 無効にすることはできません。
DT_WORD_ELLIPSIS Trimming Trimming プロパティを使用して値を WordEllipsis にします。

関連項目