tags:

views:

358

answers:

1

Hi All,

I found this link: http://msdn.microsoft.com/en-us/library/system.windows.media.formattedtext.aspx

It is an example of how to draw text by overriding the OnRender method.

I've overridden the OnRender method of the Window by using the following code, but the text is not visible. What I am doing wrong?

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));
}
A: 

Overriding OnRender for the window may not be a good thing; I would have expected it to be fine and I am still thinking that it must be something to do with the layout manager, the clipping bounds, or something related, as dropping that override into a Window class certainly calls that code. Drawing context is all deferred rendering, I'm suspecting that the parent visual either isn't using any of the drawing context or is covering it up with an opaque box from the layout.

Regardless, if you make custom control in your project and plop the OnRender code in that, and add that to the root in your xaml, this code snippet works fine.

Mikeb