gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 11:25:32 28 4
gpt4 key购买 nike

我的代码在性能方面存在一些问题......我需要将多种颜色的矩形渲染到我的 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)到我的视觉效果。但是问题是一样的(它工作得太慢并且占用大量 RAM)。

我应该怎么做才能让渲染元素的过程得到足够的时间和资源?

问候!

谢谢!

最佳答案

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

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

我创建了一个临时视觉对象,将其缩小并将其渲染为位图。最后,我将它拉伸(stretch)到我的视觉范围内。

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

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

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com