c# - 将 WPF 视觉对象渲染为图像产生纯黑色图像

标签 c# wpf image bitmapimage visualbrush

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

但是,我现在需要将图像简单地保存到磁盘,而不是将它作为一个 block 添加到固定文档中。我试过执行以下操作:

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

非常感谢!

最佳答案

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

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

关于c# - 将 WPF 视觉对象渲染为图像产生纯黑色图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6204684/

相关文章:

c# - 是否可以为整个 MVC 应用程序设置全局 RoutePrefix?

c# - 我如何查看 C# 中的远程进程?

c# - 将 MidpointRounding.AwayFromZero 设置为默认舍入方法

WPF ListView GridView DisplayMemberBinding 中心对齐内容

wpf - 动画时网格列更改宽度

html - CSS 页脚背景

c# - 如何使用 OnRender 事件但仅呈现到 WPF 中的控制区域?

c# - WPF TextBox 事件 TextChanged PreviewTextInput 不触发

php - 如何使用 asynctask 将图像从 android 上传到 php

html - 让div用动态同级填充父级的高度