Answered WPF equivalent of WinForms Control.DrawToBitmap

  • 1 พฤษภาคม 2555 18:21
     
     

    Hello,

    Winforms controls could draw themselves to a Bitmap, using the DrawToBitmap method. What is the equivalent way to do this in WPF?

ตอบทั้งหมด

  • 2 พฤษภาคม 2555 0:12
     
     คำตอบ มีโค้ด

    Hi,

    One simple way of doing it as the following

            public static void CreateBitmapFromVisual(Visual target, string fileName)
            {
                if (target == null || string.IsNullOrEmpty(fileName))
                {
                    return;
                }
    
                Rect bounds = VisualTreeHelper.GetDescendantBounds(target);
    
                RenderTargetBitmap renderTarget = new RenderTargetBitmap((Int32)bounds.Width, (Int32)bounds.Height, 96, 96, PixelFormats.Pbgra32);
    
                DrawingVisual visual = new DrawingVisual();
    
                using (DrawingContext context = visual.RenderOpen())
                {
                    VisualBrush visualBrush = new VisualBrush(target);
                    context.DrawRectangle(visualBrush, null, new Rect(new Point(), bounds.Size));
                }
    
                renderTarget.Render(visual);
                PngBitmapEncoder bitmapEncoder = new PngBitmapEncoder();
                bitmapEncoder.Frames.Add(BitmapFrame.Create(renderTarget));
                using (Stream stm = File.Create(fileName))
                {
                    bitmapEncoder.Save(stm);
                }
            }
    

    Regards,

    • ทำเครื่องหมายเป็นคำตอบโดย Sheldon _XiaoModerator 25 พฤษภาคม 2555 4:46
    •  
  • 2 พฤษภาคม 2555 23:26
     
     

    Thanks for responding. When I tried your code, the line'

    Rect bounds = VisualTreeHelper.GetDescendantBounds(target);

    returned an empty Rect.

  • 4 พฤษภาคม 2555 1:28
     
     

    What element instance you passed into it? Could you show the repro code behind here?

    Regards,

  • 25 พฤษภาคม 2555 4:46
    ผู้ดูแล
     
     

    Hi Wants2Learn,

    Yes, I am agree with Johnny CH, in WPF, if you want to draw itself to a Bitmap, you could use RenderTargetBitmap, refer to this class:

    http://msdn.microsoft.com/en-us/library/system.windows.media.imaging.rendertargetbitmap.aspx

    Best regards,


    Sheldon _Xiao[MSFT]
    MSDN Community Support | Feedback to us
    Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

  • 7 มิถุนายน 2555 10:56
     
     

    Hello,

    Sorry for the delay in getting back to you. I was calling the code too early. When I moved it into a different event, it worked correctly.