如何:将文本绘制到 Visual 中

更新:2007 年 11 月

下面的示例演示如何使用 DrawingContext 对象将文本绘制到 DrawingVisual 中。通过调用 DrawingVisual 对象的 RenderOpen 方法,返回绘制上下文。可以将图形和文本绘制到绘制上下文中。

若要将文本信息绘制到绘制上下文中,请使用 DrawingContext 对象的 DrawText 方法。将内容绘制到绘制上下文后,调用 Close 方法来关闭绘制上下文并保存内容。

示例

// Create a DrawingVisual that contains text.
private DrawingVisual CreateDrawingVisualText()
{
    // Create an instance of a DrawingVisual.
    DrawingVisual drawingVisual = new DrawingVisual();

    // Retrieve the DrawingContext from the DrawingVisual.
    DrawingContext drawingContext = drawingVisual.RenderOpen();

    // Draw a formatted text string into the DrawingContext.
    drawingContext.DrawText(
       new FormattedText("Click Me!",
          CultureInfo.GetCultureInfo("en-us"),
          FlowDirection.LeftToRight,
          new Typeface("Verdana"),
          36, System.Windows.Media.Brushes.Black),
          new System.Windows.Point(200, 116));

    // Close the DrawingContext to persist changes to the DrawingVisual.
    drawingContext.Close();

    return drawingVisual;
}
说明:

有关上述代码示例所摘自的完整代码示例,请参见使用 DrawingVisual 进行命中测试示例