如何:创建空心文字

更新:2007 年 11 月

在大多数情况下,向 Windows Presentation Foundation (WPF) 应用程序中的文本字符串添加装饰时,您可以使用离散字符或标志符号集合形式的文本。例如,可创建线性渐变画笔,并将其应用于 TextBox 对象的 Foreground 属性。当显示或编辑文本框时,线性渐变画笔将自动应用于文本字符串中的当前字符集。

应用于文本框的线性渐变画笔的示例

使用线性渐变画笔显示的文本

但是,您还可以将文本转换为 Geometry 对象,这样便可以创建其他类型的可视化多格式文本。例如,可以基于文本字符串的轮廓创建 Geometry 对象。

应用于文本轮廓几何图形的线性渐变画笔的示例

使用线性渐变画笔的文本轮廓

将文本转换为 Geometry 对象时,它不再是字符的集合 - 您不能修改文本字符串中的字符。但是,可以修改已转换文本的笔画和填充属性,以此来影响该文本的外观。笔画指的是已转换文本的轮廓;填充指的是已转换文本的轮廓的内部区域。

下面的示例演示几种通过修改已转换文本的笔画和填充来创建视觉效果的方法。

将笔画和填充设置为不同颜色的示例

对填充和笔画使用不同颜色的文本

应用于笔画的图像画笔的示例

笔画应用了图像画笔的文本

还可以修改已转换文本的边界框矩形或高光点。下面的示例演示一种通过修改已转换文本的笔画和高光点来创建视觉效果的方法。

应用于笔画和高光点的图像画笔的示例

笔画应用了图像画笔的文本

说明:

有关下面的代码示例所提取自的完整代码示例,请参见空心效果文字自定义控件的示例

示例

将文本转换为 Geometry 对象的关键是使用 FormattedText 对象。一旦创建该对象之后,即可使用 BuildGeometryBuildHighlightGeometry 方法将文本转换为 Geometry 对象。第一个方法返回格式化文本的几何图形;第二个方法返回格式化文本的边界框的几何图形。下面的代码示例演示如何创建 FormattedText 对象以及如何检索格式化文本及其边界框的几何图形。

/// <summary>
/// Create the outline geometry based on the formatted text.
/// </summary>
public void CreateText()
{
    System.Windows.FontStyle fontStyle = FontStyles.Normal;
    FontWeight fontWeight = FontWeights.Medium;

    if (Bold == true) fontWeight = FontWeights.Bold;
    if (Italic == true) fontStyle = FontStyles.Italic;

    // Create the formatted text based on the properties set.
    FormattedText formattedText = new FormattedText(
        Text,
        CultureInfo.GetCultureInfo("en-us"),
        FlowDirection.LeftToRight,
        new Typeface(
            Font,
            fontStyle,
            fontWeight,
            FontStretches.Normal),
        FontSize,
        System.Windows.Media.Brushes.Black // This brush does not matter since we use the geometry of the text. 
        );

    // Build the geometry object that represents the text.
    _textGeometry = formattedText.BuildGeometry(new System.Windows.Point(0, 0));

    // Build the geometry object that represents the text hightlight.
    if (Highlight == true)
    {
        _textHighLightGeometry = formattedText.BuildHighlightGeometry(new System.Windows.Point(0, 0));
    }
}

要显示检索的 Geometry 对象,您需要访问正在显示已转换文本的对象的 DrawingContext。在这些代码示例中,这是通过创建自定义控件对象来执行的,该自定义控件对象从支持用户定义呈现的类派生而来。有关创建自定义控件的详细信息,请参见空心效果文字自定义控件的示例

若要显示自定义控件中的 Geometry 对象,请重写 OnRender 方法。重写后的方法应使用 DrawGeometry 方法来绘制 Geometry 对象。

/// <summary>
/// OnRender override draws the geometry of the text and optional highlight.
/// </summary>
/// <param name="drawingContext">Drawing context of the OutlineText control.</param>
protected override void OnRender(DrawingContext drawingContext)
{
    // Draw the outline based on the properties that are set.
    drawingContext.DrawGeometry(Fill, new System.Windows.Media.Pen(Stroke, StrokeThickness), _textGeometry);

    // Draw the text highlight based on the properties that are set.
    if (Highlight == true)
    {
        drawingContext.DrawGeometry(null, new System.Windows.Media.Pen(Stroke, StrokeThickness), _textHighLightGeometry);
    }
}

请参见

任务

空心效果文字自定义控件的示例

概念

绘制格式化文本