2

我正在尝试从 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");
    }

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

4

1 回答 1

4

紧随其后添加border.ApplyTemplate

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

您的边框在保存之前没有自行更新。

于 2010-08-01T11:36:19.363 回答