asp.net - 在 ASP.NET 中生成 WPF UIElement 位图

标签 asp.net wpf uielement rendertargetbitmap

我正在尝试生成 WPF 边框外的位图。整个事情位于运行 .net 4.0 的 asp.net 应用程序(当然是服务器端)中。

问题是,生成的图像是空的。有人知道为什么吗?

这是代码。

public static byte[] Draw(int width, int height)
    {
        MemoryStream memoryStream
            = new MemoryStream();
        Thread t = new Thread(delegate()
            {
                System.Windows.Controls.Border border = new System.Windows.Controls.Border()
                {
                    Background = Brushes.Red,
                    BorderBrush = Brushes.Green,
                    CornerRadius = new System.Windows.CornerRadius(5),
                    Width = width,
                    Height = height
                };

                border.ApplyTemplate();

                RenderTargetBitmap renderTargetBitmap = 
                    new RenderTargetBitmap(width, height, 90, 90, PixelFormats.Pbgra32);

                renderTargetBitmap.Render(border);

                BitmapEncoder bitmapEncoder = 
                    new PngBitmapEncoder();

                bitmapEncoder.Frames.Add(BitmapFrame.Create(renderTargetBitmap));
                bitmapEncoder.Save(memoryStream);
            });
        t.SetApartmentState(ApartmentState.STA);
        t.Start();
        bool success = t.Join(5000);

        if (success)
            return memoryStream.ToArray();
        else
            throw new Exception("Fail");
    }

结果非常糟糕,正如我所说,它返回了具有正确宽度和高度的图像,但它是空的,所以我想我不会用线程位搞乱它。

最佳答案

border.ApplyTemplate之后添加:

border.Measure(new Size(width, height));
border.Arrange(new Rect(0, 0, width, height));
border.UpdateLayout();

在保存之前,您的边框不会自行更新。

关于asp.net - 在 ASP.NET 中生成 WPF UIElement 位图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3381351/

相关文章:

c# - web.config 转换 - 从 connectionstring 部分删除注释

c# - Linq to SQL 背后的安全性

mysql - SetInitializer用于数据库错误

c# - 在没有参数的另一个函数中使用一个函数的变量?

c# - WindowClosing方法发生异常时WPF应用程序关闭

wpf - 如何监听 Co​​llectionChanged 事件并执行某些方法

c# - 保存呈现的 UIElement 图像大于它在屏幕上显示的图像

c# - CollectionView 与 WPF(或类似的东西)

iOS 修改使用 IB 创建的 UIElements 的图层

c# - WPF 中 UIElement 的核心属性是什么?