从UIElement获取图像将被裁剪为显示的大小

时间:2011-08-12 10:48:39

标签: c# wpf image image-processing uielement

我正在使用此代码拍摄wpf控件的图像:

BitmapEncoder imgEncoder = new PngBitmapEncoder();
RenderTargetBitmap bmpSource = new RenderTargetBitmap((int)element.ActualWidth, (int)element.ActualHeight, 150, 150, PixelFormats.Pbgra32);
bmpSource.Render(element);
imgEncoder.Frames.Add(BitmapFrame.Create(bmpSource));
using (MemoryStream ms = new MemoryStream())
{
    imgEncoder.Save(ms);
    bytes = ms.ToArray();
    ms.Position = 0;
    Image i = Image.FromStream(ms);
    i.Save(@"C:\" + Guid.NewGuid().ToString() + "LARGE.png");
}

问题是ActualHeight/Width属性给出了渲染的高度和宽度,即显示的部分。我想保存整个控件的图像,即使屏幕上看不到某些控件,即它放在滚动查看器中。

如何获取控件的完整大小/高度,以便bmpSource.Render()将整个控件呈现给图像?

2 个答案:

答案 0 :(得分:1)

     private static void SaveUsingEncoder(string fileName, FrameworkElement UIElement, BitmapEncoder encoder)
    {
        int height = (int)UIElement.ActualHeight;
        int width = (int)UIElement.ActualWidth;

        // These two line of code make sure that you get completed visual bitmap.
        // In case your Framework Element is inside the scroll viewer then some part which is not
        // visible gets clip.  
        UIElement.Measure(new System.Windows.Size(width, height));
        UIElement.Arrange(new Rect(new System.Windows.Point(), new Point(width, height)));

        RenderTargetBitmap bitmap = new RenderTargetBitmap(width,

                                                                height,
                                                                96, // These decides the dpi factors 
                                                                96,// The can be changed when we'll have preview options.
                                                                PixelFormats.Pbgra32);
        bitmap.Render(UIElement);

        SaveUsingBitmapTargetRenderer(fileName, bitmap, encoder);
    }


     private static void SaveUsingBitmapTargetRenderer(string fileName, RenderTargetBitmap renderTargetBitmap, BitmapEncoder bitmapEncoder)
    {
        BitmapFrame frame = BitmapFrame.Create(renderTargetBitmap);
        bitmapEncoder.Frames.Add(frame);
        // Save file .
        using (var stream = File.Create(fileName))
        {
            bitmapEncoder.Save(stream);
        }
    }

将此功能称为

     SaveUsingEncoder(fileName, frameworkElement, new PngBitmapEncoder());

希望这会有所帮助。

答案 1 :(得分:0)

您可以尝试暂时将控件从其上下文中取出(如果绑定可能会导致问题),将其转换为可见点或将其滚动到视图中进行渲染。