How to: Create a Bitmap from a Visual

This example shows how you can create a bitmap from a Visual. A DrawingVisual is rendered with FormattedText. The Visual is then rendered to the RenderTargetBitmap creating a bitmap of the given text.

Example

Image myImage = new Image();
FormattedText text = new FormattedText("ABC",
        new CultureInfo("en-us"),
        FlowDirection.LeftToRight,
        new Typeface(this.FontFamily, FontStyles.Normal, FontWeights.Normal, new FontStretch()),
        this.FontSize,
        this.Foreground);

DrawingVisual drawingVisual = new DrawingVisual();
DrawingContext drawingContext = drawingVisual.RenderOpen();
drawingContext.DrawText(text, new Point(2, 2));
drawingContext.Close();

RenderTargetBitmap bmp = new RenderTargetBitmap(180, 180, 120, 96, PixelFormats.Pbgra32);
bmp.Render(drawingVisual);
myImage.Source = bmp;

See Also

Reference

DrawingContext

Concepts

Imaging Overview
Drawing Objects Overview
Using DrawingVisual Objects