我的代码存在一些性能问题... 我需要将多种颜色的矩形渲染到我的 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);
}
我创建了一个临时视觉对象,将其缩小并将其渲染为位图。最后我把它延伸到我的视觉上。
关于c# - 将许多元素渲染到 DrawingVisual,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9486928/