将 WPF 视觉对象渲染为图像会生成纯黑色图像
在 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 到图像的方法,但除了上述内容之外,没有找到任何东西,似乎可以满足我的需要。
非常感谢!
In a C#/WPF application, I have a DataChart object that I need to save to an image. Currently, the object is added to a Fixed Document and correctly displays on that Fixed Document by using the following code:
VisualBrush chartBrush = new VisualBrush(chart);
Rectangle chartRect = new Rectangle();
chartRect.Height = chartClone.Height;
chartRect.Width = chartClone.Width;
chartRect.Fill = chartBrush;
AddBlockUIElement(chartRect, textAlignment);
However, rather than add it as a block to a Fixed Document, I now need to simply save the image to disk. I've tried doing the following:
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();
}
However, this simply gives me a solid black image in the size of my chart and I cannot figure out why.
So my question is, does anyone know of a better way to turn the DataChart object into a PNG or BMP image I can save? I've tried searching on getting from a VisualBrush or a Rectangle to an image, but haven't found anything, other than the above, that seems to do what I need.
Thanks so much!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
看看您是否可以使用下面的代码:
See if you can work with the code below:
将此行替换
为这样的
replace this line
with such