呈现“不可见”的效果位图图像的 WPF 控件

发布于 2024-11-04 18:42:48 字数 523 浏览 0 评论 0 原文

正如我今天发现的那样,将 WPF 控件渲染为位图图像并不是一项简单的任务。据我所知,现在处理父控件边距是一个问题,正如 Rick Strahl 在他的博客

http://www.west-wind.com/weblog/posts/2007/Sep/10/Rendering-a-WPF-Container-to-Bitmap

到目前为止,我能够创建窗口内可见的任何控件的位图,但我真正需要做的是创建不可见控件的位图。我只是在代码中创建它们 - 简单的形状,如矩形和椭圆形 - 并希望将它们作为位图保存到磁盘。 对我来说,这简直就是一场个人噩梦。由于我的 ActualHeight 和 ActualWidth 始终为 0,所以我使用 Height 和 Width 来代替。但我得到的只是一个与我的控件大小相同的空图像。

如何创建任何控件的位图而不将其添加到可见窗口?

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

http://www.west-wind.com/weblog/posts/2007/Sep/10/Rendering-a-WPF-Container-to-Bitmap

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

国粹 2024-11-11 18:42:48

新元素尚未执行布局。在渲染之前,您需要在控件上调用 Measure 和 Arrange。

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

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);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文