#241 – Rendering Text Using DrawText

You can render text into a visual using the DrawText method of a DrawingContextDrawText renders text that is represented by an instance of FormattedText into the drawing context at a specified location.

Below is an example of drawing some text into a custom DrawingVisual.

    class MyDrawingVisual : DrawingVisual
    {
        public MyDrawingVisual()
        {
            using (DrawingContext dc = RenderOpen())
            {
                // Create formatted text--in a particular font at a particular size
                FormattedText ft = new FormattedText(
                    "When things are at their worst I find something always happens.",
                    CultureInfo.CurrentCulture,
                    FlowDirection.LeftToRight,
                    new Typeface(new FontFamily("Century"), FontStyles.Normal, FontWeights.Bold, FontStretches.Normal),
                    24,    // 36 pt type
                    Brushes.Black);

                // Draw the text at a location
                dc.DrawText(ft, new Point(10.0, 10.0));
            }
        }
    }

Once we host this DrawingVisual in an UIElement, we can see the text in a window:

Advertisement