Procedura: creare un oggetto Bitmap da un oggetto Visual

In questo esempio viene illustrato come creare una bitmap da un oggetto Visual. Viene eseguito il rendering di un DrawingVisual oggetto con FormattedText. Viene Visual quindi eseguito il rendering dell'oggetto alla RenderTargetBitmap creazione di una bitmap del testo specificato.

Esempio

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;
Dim myImage As New Image()
Dim [text] As New FormattedText("ABC", New CultureInfo("en-us"), System.Windows.FlowDirection.LeftToRight, New Typeface(Me.FontFamily, FontStyles.Normal, FontWeights.Normal, New FontStretch()), Me.FontSize, Me.Foreground)

Dim drawingVisual As New DrawingVisual()
Dim drawingContext As DrawingContext = drawingVisual.RenderOpen()
drawingContext.DrawText([text], New System.Windows.Point(2, 2))
drawingContext.Close()

Dim bmp As New RenderTargetBitmap(180, 180, 120, 96, PixelFormats.Pbgra32)
bmp.Render(drawingVisual)
myImage.Source = bmp

Vedi anche