绘图控制内存(位图) [英] Drawing control to memory (Bitmap)

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

问题描述

是否有可能没有在屏幕上的所有图纸绘制WPF控件内存(位图)?结果
我发现如何保存为位图的例子,但它只有当窗口在屏幕绘制工作

 的BitmapImage位=新的BitmapImage();
    RenderTargetBitmap的RenderTarget =
    新RenderTargetBitmap((INT)canvaspad.Width,
    (INT)canvaspad.Height,
    96,
    96,
    System.Windows.Media.PixelFormats.Default);
renderTarget.Render(canvaspad);


解决方案

由于控制没有父容器,你需要调用的测量和的排列为了做一个适当的布局。由于布局是异步完成(见测量和安排),你还需要调用 UpdateLayout请迫使布局进行更新立即生效。

 公开的BitmapSource RenderToBitmap(的UIElement元素,尺寸大小)
{
    element.Measure(大小);
    element.Arrange(新矩形(尺寸));
    element.UpdateLayout();    VAR位=新RenderTargetBitmap(
        (INT)size.Width,(INT)size.Height,96,96,PixelFormats.Default);    bitmap.Render(元件);
    返回位图;
}


如果你已经设置了宽度高度元素,你可以使用的大小参数

  VAR电网=新格
{
    宽度= 200,
    高度= 200,
    背景= Brushes.Yellow
};grid.Children.Add(
    新的椭圆
    {
        宽度= 100,
        高度= 100,
        填写= Brushes.Blue
    });VAR位= RenderElement(电网,新尺寸(grid.Width,grid.Height));

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

解决方案

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


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

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆