【问题标题】:Rendering WPF Visual Object as Image Yields Solid Black Image将 WPF 视觉对象渲染为图像会产生纯黑色图像
【发布时间】:2011-09-06 11:24:56
【问题描述】:

在 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 到图像,但除了上述之外,没有找到任何似乎可以满足我需要的东西。

非常感谢!

【问题讨论】:

  • 坏消息是我很确定这是驱动程序/显卡问题,因为它应该可以工作。尝试更新您的驱动程序或在另一台计算机(或不同的操作系统)上尝试您的代码。仍在研究一些好消息:)

标签: c# wpf image bitmapimage visualbrush


【解决方案1】:

替换这一行

image.Frames.Add(BitmapFrame.Create(BitmapRender));

这样的

image.Frames.Add(BitmapFrame.Create(bmp));

【讨论】:

  • 对不起,这实际上是一个错字——我已经这样了,当我问这个问题时它只是改变了。不过感谢您的收获!
  • 我在我的项目中使用了这样的代码pastebin.com/up3JGuFw,它工作得非常完美。
【解决方案2】:

看看你是否可以使用下面的代码:

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); 

【讨论】:

  • 这产生了完全相同的东西——一个大的、纯黑色的矩形。
猜你喜欢
  • 1970-01-01
  • 2016-07-23
  • 1970-01-01
  • 2014-10-12
  • 2018-04-27
  • 2011-11-26
  • 1970-01-01
  • 2011-01-10
  • 1970-01-01
相关资源
最近更新 更多