Render text filled with an image in a WPF program using C#

[Render text filled with an image]

The example Render outlined text in a WPF program using C# shows how to draw text that is filled with one color and outlined with another. This example uses the following overridden OnRender to render text filled with an image. The code in blue shows where this example differs from the previous one.

protected override void OnRender(DrawingContext drawingContext)
    // Clear the background.
    Rect bg_rect = new Rect(0, 0, ActualWidth, ActualHeight);
    drawingContext.DrawRectangle(Brushes.White, null, bg_rect);

    // Create the FormattedText.
    const double fontsize = 70;
    FontFamily font_family = new FontFamily("Verdana");
    Typeface typeface = new Typeface("Verdana");
    FormattedText formatted_text = new FormattedText("Flowers",
        CultureInfo.CurrentCulture, FlowDirection.LeftToRight,
        typeface, fontsize, Brushes.Black);

    // Center horizontally.
    formatted_text.TextAlignment = TextAlignment.Center;

    // Pick an origin to center the text.
    Point origin = new Point(
        grdMain.ActualWidth / 2,
        (grdMain.ActualHeight - formatted_text.Height) / 2);

    // Convert the text into geometry.
    Geometry geometry = formatted_text.BuildGeometry(origin);

    // Make an image brush.
    ImageSource flowers_source = new BitmapImage(
        new Uri("Flowers.jpg", UriKind.Relative));
    ImageBrush flowers_brush = new ImageBrush(flowers_source);
    flowers_brush.Stretch = Stretch.UniformToFill;

    // Draw the geometry.
    Pen pen = new Pen(Brushes.Green, 2);
    drawingContext.DrawGeometry(flowers_brush, pen, geometry);

See the previous example for most of the details. The main difference in this example is that it fills the text with an ImageBrush instead of a solid brush.

To make the ImageBrush, the code first needs to make a BitmapImage holding the image. To do that, I used the Project menu’s Add Existing Item command to add the image file to the project at design time. I then selected that file in Solution Explorer, set its “Build Action” property to “Content,” and set its “Copy to Output Directory” property to “Copy if newer.” Now when you build the program, that file is copied into the output directory (where the executable is created) if it has changed since the last time you built the program.

The code then passes the bitmap file’s name into the BitmapImage class’s constructor. It passes the resulting BitmapImage into the ImageBrush constructor to create the brush. Finally the code calls the DrawingContext object’s DrawGeometry method to draw the text, filling it with the ImageBrush and outlining it with a solid green pen.


This entry was posted in drawing, geometry, graphics, wpf, XAML and tagged , , , , , , , , , , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *