在C#/ WPF应用程序中,我有一个需要保存到图像的DataChart对象。目前,该对象被添加到固定文档中,并使用以下代码正确显示在该固定文档上:
VisualBrush chartBrush = new VisualBrush(chart);
Rectangle chartRect = new Rectangle();
chartRect.Height = chartClone.Height;
chartRect.Width = chartClone.Width;
chartRect.Fill = chartBrush;
AddBlockUIElement(chartRect, textAlignment);
但是,我现在只需将图像保存到磁盘,而不是将其作为块添加到固定文档中。我尝试过以下操作:
RenderTargetBitmap bmp = new RenderTargetBitmap((int)chart.Width, (int)chart.Height, 96, 96, PixelFormats.Default);
bmp.Render(chart);
PngBitmapEncoder image = new PngBitmapEncoder();
image.Frames.Add(BitmapFrame.Create(bmp));
using (Stream fs = File.Create("TestImage.png"))
{
image.Save(fs);
fs.Close();
}
然而,这只是给我一张图表大小的黑色图像,我无法弄清楚原因。
所以我的问题是,有没有人知道将DataChart对象转换为我可以保存的PNG或BMP图像的更好方法?我已经尝试过从VisualBrush或Rectangle到图像的搜索,但除了上面的内容之外,还没有找到任何可能做我需要的东西。
非常感谢!
答案 0 :(得分:-1)
看看您是否可以使用以下代码:
VisualBrush target = new VisualBrush(element);
DrawingVisual visual = new DrawingVisual();
DrawingContext dc = visual.RenderOpen();
dc.DrawRectangle(target, null, new Rect(0, 0,
width,
height));
dc.Close();
RenderTargetBitmap bmp = new RenderTargetBitmap(
(int)width,
(int)height, 96, 96, PixelFormats.Pbgra32);
bmp.Render(visual);
答案 1 :(得分:-1)
替换此行
image.Frames.Add(BitmapFrame.Create(BitmapRender));
有这样的
image.Frames.Add(BitmapFrame.Create(bmp));