c# - 将许多元素渲染到 DrawingVisual

标签 c# wpf performance

我的代码存在一些性能问题... 我需要将多种颜色的矩形渲染到我的 DrawingVisual。

第一个版本很简单:

using (DrawingContext dc = Canvas.RenderOpen())
{
   for (Int32 x = 0; x < widthCount; x++)
      for (Int32 y = 0; y < heightCount; y++)
      {
          Color c;
          Double value = mass[x, y];
          c = GetColorByValue(value);
          dc.DrawRectangle(new SolidColorBrush(c), null,
          new Rect(x * step - step / 2, y * step - step / 2, step, step));
       }
}

在矩形数量约为 250x250 的情况下(并且它具有 200Mb RAM),它可以正常工作。但如果它们的数量是 750x750,渲染过程会太长且缓慢(需要超过 2.5Gb RAM)

下一步是使用像缓冲区一样的位图。但是我的 DrawingVisual 的大小有问题。视觉效果确实很大。 因此不可能创建全尺寸位图,因为 RenderTargetBitmap 的构造函数会抛出异常“图像数据在处理过程中产生溢出”。

最后,我创建了一个小位图并将其拉伸(stretch)到我的视觉效果。然而问题是一样的(它运行速度太慢并且占用大量内存)。

我应该怎样做才能使渲染元素的过程获得足够的时间和资源?

问候!

谢谢!

最佳答案

是的!我已经找到解决这个问题的方法了! 我第一次错误地使用位图作为缓冲区。 但现在我正确地使用了它。 我的代码:

//temp visual
DrawingVisual tmpVisual = new DrawingVisual();
using (DrawingContext dc = tmpVisual.RenderOpen())
{
     for (Int32 x = 0; x < widthCount; x++)
          for (Int32 y = 0; y < heightCount; y++)
          {
              Color c;
              Double value = mass[x, y];
              c = GetColorByValue(value);
              dc.DrawRectangle(new SolidColorBrush(c), null,
                  new Rect(x * step - step / 2, y * step - step / 2, step, step));
          }
}

//resize visual
tmpVisual.Transform = new ScaleTransform(maxWidth/(widthCount * step),
                        maxHeight/(heightCount * step));

//visual to bitmap
RenderTargetBitmap bitmap = 
    new RenderTargetBitmap(maxWidth, maxHeight, 96, 96, PixelFormats.Pbgra32);
bitmap.Render(tmpVisual);

using (DrawingContext dc = Canvas.RenderOpen())
{
    Rect rect = new Rect(0, 0, widthCount * step, heightCount * step);
    dc.DrawImage(bitmap, rect);
}

我创建了一个临时视觉对象,将其缩小并将其渲染为位图。最后我把它延伸到我的视觉上。

感谢这个主题:Scaling WPF content before rendering to bitmap

关于c# - 将许多元素渲染到 DrawingVisual,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9486928/

相关文章:

c# - 创建自定义可视化工具

c# - 无法在 list 资源中找到报告

c# - WPF 数据虚拟化和 DataGrid

wpf - 滚动查看器的子元素阻止用鼠标滚轮滚动?

c++ - 随着线程数的增加,Lua 会扼杀多线程性能(包括条形图)

c# - WCF:如何为类型中的类型构造 DataContract

c# - 如何使用 MultipartFormDataContent 为 HttpClient 请求设置 Content-Type header ?

c# - 在资源字典中的同一程序集中引用 WPF 控件类

performance - SIMD/SSE 新手 : simple image filtering

c++ - 模拟加速大于最佳