Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF Copy image of control to bitmap

Tags:

c#

wpf

I'm using a third party control, and I would like to create a bitmap from the control (either to put on the clipboard or save to a png).

I have tried using a RenderBitmapTarget, but it will only copy the control as it is rendered on the screen (my grid is bigger than the screen).

My RenderBitmapTarget code looks like this:

RenderTargetBitmap rtb = new RenderTargetBitmap((int)control.ActualWidth, (int)control.ActualHeight, 96, 96, PixelFormats.Pbgra32);
rtb.Render(control);
PngBitmapEncoder png = new PngBitmapEncoder();
png.Frames.Add(BitmapFrame.Create(rtb));
MemoryStream stream = new MemoryStream();
png.Save(stream);
Image image = Image.FromStream(stream);

I've tried specifying a larger size (both in the RenderTargetBitmap constructor, and specifying new width/height for the control, but both just yielded the same image on a larger canvas.

Any thoughts?

like image 753
David Hope Avatar asked Sep 19 '25 10:09

David Hope


1 Answers

Here is what I ended up with...

        tempWidth = myControl.ActualWidth;
        tempHeight = myControl.ActualHeight;

        myControl.Width = double.NaN;
        myControl.Height = double.NaN;

        myControl.UpdateLayout();

        RenderTargetBitmap rtb = new RenderTargetBitmap((int)myControl.ActualWidth, (int)myControl.ActualHeight, 96, 96, PixelFormats.Pbgra32);

        rtb.Render(myControl);

        PngBitmapEncoder pbe = new PngBitmapEncoder();
        pbe.Frames.Add(BitmapFrame.Create(rtb));
        MemoryStream stream = new MemoryStream();
        pbe.Save(stream);
        image = (System.Drawing.Bitmap)System.Drawing.Image.FromStream(stream);

        CEGrid.Width = tempWidth;
        CEGrid.Height = tempHeight;
like image 108
David Hope Avatar answered Sep 21 '25 02:09

David Hope