What is the best way to draw text along with geometry?

fury picture fury · Jun 24, 2009 · Viewed 11k times · Source

In WPF, I'm starting to use classes such as LineGeometry, EllipseGeometry, GeometryGroup, Path... in order to draw 2D graphics. I chose these over shapes because I saw it could be faster thanks to the freezing feature.

I need to draw text along with geometry, with specific fonts. The text needs to be positionnable with the same coordinate system as the geometry. And I need to be able to apply a transform such as RotateTransform.

What would be the best way? I've run across the GlyphRunDrawing class but it's really complicated.

Thanks a lot in advance.

Answer

Nir picture Nir · Jun 24, 2009

To create a text geometry just use FormattedText.BuildGeometry, for example, to get a geometry of "Text to display" in font Tahoma size 16 pixels at point (5,5) use:

    FormattedText text = new FormattedText("Text to display",
        CultureInfo.CurrentCulture,
        FlowDirection.LeftToRight,
        new Typeface("Tahoma"),
        16,
        Brushes.Black);
    Geometry geometry = text.BuildGeometry(new Point(5, 5));

If you need to do this in XAML you can wrap up this code in a MarkupExtention