Getting Image from UIElement is cropped to displayed size
I am taking an image of a wpf control using this code:
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");
}
The trouble 开发者_JAVA技巧is ActualHeight/Width
property gives the rendered height and width i.e. the displayed part. I want to save an image of the whole control even if some of the control is not visible on the screen i.e. it is placed in a scrollviewer.
How can I get the full size / height of a control so the bmpSource.Render() renders the whole control to an image?
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);
}
}
Call this function as
SaveUsingEncoder(fileName, frameworkElement, new PngBitmapEncoder());
Hope this will help.
You could try temporarily taking the control out of its context (might cause problems if bound),transform it to a visivible point or scroll it into view for rendering.
精彩评论