渲染"不可见" WPF控件的位图图像 [英] Render a "not visible" WPF controls to an bitmap image

查看:180
本文介绍了渲染"不可见" WPF控件的位图图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

渲染一个WPF控件位图图像不是一个简单的任务,因为我今天发现了。据我所知,现在对付父母的控制范围是一个问题,因为里克在施特拉尔他的博客中写道:

Render a WPF control to a bitmap image is not a trivial task as I found out today. As I know now dealing with the parent control margin is a problem, as Rick Strahl wrote in his blog

<一个href=\"http://www.west-wind.com/weblog/posts/2007/Sep/10/Rendering-a-WPF-Container-to-Bitmap\">http://www.west-wind.com/weblog/posts/2007/Sep/10/Rendering-a-WPF-Container-to-Bitmap

到目前为止,我可以创造一个窗口中可见,但我真正需要做的是创造无形的控制位图任何控制的位图。 simples的形状像矩形和椭圆 - - 我只是在code创建它们,并希望它们保存为位图到磁盘。
对我来说,这变成是个人的噩梦。由于我的ActualHeight和ActualWidth的始终是0我使用的高度和宽度来代替。但我得到的是在我的控制大小的空图像。

So far I am able to create bitmaps of any control that is visible inside a window but what I really need to do is create bitmaps of invisible controls. I just create them in code - simples shapes like rectangle and ellipse - and want to save them as bitmaps to disk. For me this turn out to be a personal nightmare. Since my ActualHeight and ActualWidth is always 0 I use Height and Width instead. But all I get is a empty image in the size of my control.

我怎样才能创建任何控制的位图,而不将其添加到一个可见的窗口?

How can I create a bitmap of any control without adding it to a visible window?

推荐答案

它们的布局进行了新的元素都没有。你需要调用测量与控制安排你渲染它。

New elements haven't had their layout performed. You need to call Measure and Arrange on the control before you render it.

Canvas c = new Canvas();

Rectangle r = new Rectangle
{
    Fill = Brushes.Orange,
    Width = 200,
    Height = 100
};

Ellipse e = new Ellipse
{
    Fill = Brushes.DodgerBlue,
    Width = 100,
    Height = 100
};

Canvas.SetLeft(e, 150);

c.Children.Add(r);
c.Children.Add(e);

var size = new Size(250,100);
c.Measure(size);
c.Arrange(new Rect(size));

RenderTargetBitmap bmp = new RenderTargetBitmap(250, 100, 96, 96, PixelFormats.Pbgra32);

bmp.Render(c);

PngBitmapEncoder enc = new PngBitmapEncoder();
enc.Frames.Add(BitmapFrame.Create(bmp));

using(var s = File.OpenWrite("image.png"))
    enc.Save(s);

这篇关于渲染&QUOT;不可见&QUOT; WPF控件的位图图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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