wpf 利用 RenderTargetBitmap把控件保存为图片

 Stream GetImageFromControl(Control control)
        {
            MemoryStream ms = null;

            DrawingVisual drawingVisual = new DrawingVisual();
            using (DrawingContext context = drawingVisual.RenderOpen())
            {
                VisualBrush brush = new VisualBrush(gd) { Stretch = Stretch.None };
                context.DrawRectangle(brush, null, new Rect(0, 0, gd.Width, gd.Height));
                context.Close();
            }

            //dpi可以自己设定   // 获取dpi方法:PresentationSource.FromVisual(this).CompositionTarget.TransformToDevice
            RenderTargetBitmap bitmap = new RenderTargetBitmap((int)gd.Width, (int)gd.Height, 96, 96, PixelFormats.Pbgra32);
            bitmap.Render(drawingVisual);

            PngBitmapEncoder encode = new PngBitmapEncoder();
            encode.Frames.Add(BitmapFrame.Create(bitmap));
            ms = new MemoryStream();
            encode.Save(ms);

            return ms;
        }

你可能感兴趣的:(bitmap)