我正在尝试生成 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/