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;
        }
posted @ 2011-03-29 16:03  xiaokang088  阅读(11022)  评论(4编辑  收藏  举报