Vahid
Vahid

Reputation: 5444

How to convert DrawingVisual to Bitmap in WPF C#

I'm using the following code to draw text on DrawingVisual. I've heard that you can use RenderTargetBitmap to convert this to Bitmap to have better performance.

public class ModelBeamSectionNamesInPlan : UIElement
{
    private readonly VisualCollection _visuals;
    public ModelBeamSectionNamesInPlan(BaseWorkspace space)
    {
        var typeface = Settings.BeamTextTypeface;
        var cultureinfo = Settings.CultureInfo;
        var flowdirection = Settings.FlowDirection;
        var beamtextsize = Settings.BeamTextSize;
        var beamtextcolor = Settings.InPlanBeamTextColor;

        const double scale = 0.5;

        _visuals = new VisualCollection(this);
        foreach (var beam in Building.ModelBeamsInTheElevation)
        {
            var drawingVisual = new DrawingVisual();
            using (var dc = drawingVisual.RenderOpen())
            {
                var text = beam.Section.Id;
                var ft = new FormattedText(text, cultureinfo, flowdirection,
                                           typeface, beamtextsize, beamtextcolor, 
                                           null, TextFormattingMode.Display)
                {
                    TextAlignment = TextAlignment.Center
                };

                // Draw Text
                dc.DrawText(ft, space.FlipYAxis(x, y));
            }
            _visuals.Add(drawingVisual);
        }
    }

    protected override Visual GetVisualChild(int index)
    {
        return _visuals[index];
    }

    protected override int VisualChildrenCount
    {
        get
        {
            return _visuals.Count;
        }
    }
}

And finally I'm using the below code to add the texts to Canvas:

var beamtexts = new ModelBeamSectionNamesInPlan(this);
MyCanvas.Children.Add(beamtexts);

I don't have the slightest clue where I should use the RenderTargetBitmap to convert to BMP and how to add it to MyCanvas?

In the RenderTargetBitmap documentation example I have found this:

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

But I don't know how to implement this in my code.

Upvotes: 0

Views: 1211

Answers (0)

Related Questions