问题描述
是否可以将wpf控件绘制到内存(位图)而不在屏幕上绘制?
我找到了一个关于如何保存到 Bitmap 的示例,但它仅在屏幕中绘制了窗口时才有效.
Is it possible to draw a wpf control to memory (Bitmap) without drawing on the screen at all?
I found an example of how to save to Bitmap, but it only works when the window has been drawn in the screen.
BitmapImage bitmap = new BitmapImage();
RenderTargetBitmap renderTarget =
new RenderTargetBitmap((int)canvaspad.Width,
(int)canvaspad.Height,
96,
96,
System.Windows.Media.PixelFormats.Default);
renderTarget.Render(canvaspad);
推荐答案
由于控件没有父容器,需要调用Measure 和 安排以进行适当的布局.由于布局是异步完成的(请参阅 Measure 和 Arrange),您可能还需要调用 UpdateLayout 强制布局为立即更新.
As the control has no parent container, you need to call Measure and Arrange in order to do a proper layout. As layout is done asynchronously (see Remarks in Measure and Arrange), you may also need to call UpdateLayout to force the layout to be updated immediately.
public BitmapSource RenderToBitmap(UIElement element, Size size)
{
element.Measure(size);
element.Arrange(new Rect(size));
element.UpdateLayout();
var bitmap = new RenderTargetBitmap(
(int)size.Width, (int)size.Height, 96, 96, PixelFormats.Default);
bitmap.Render(element);
return bitmap;
}
<小时>
如果您已经设置了元素的Width
和Height
,您可以将其用于大小参数:
In case you have already set the Width
and Height
of the element you may use that for the size parameter:
var grid = new Grid
{
Width = 200,
Height = 200,
Background = Brushes.Yellow
};
grid.Children.Add(
new Ellipse
{
Width = 100,
Height = 100,
Fill = Brushes.Blue
});
var bitmap = RenderElement(grid, new Size(grid.Width, grid.Height));
这篇关于绘图控件到内存(位图)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!