绘图控件到内存(位图)

Drawing control to memory (Bitmap)(绘图控件到内存(位图))
本文介绍了绘图控件到内存(位图)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以将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;
}

<小时>

如果您已经设置了元素的WidthHeight,您可以将其用于大小参数:


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));

这篇关于绘图控件到内存(位图)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)