【问题标题】:Need something to draw many images quickly in WPF需要一些东西在 WPF 中快速绘制许多图像
【发布时间】:2011-02-16 18:53:02
【问题描述】:

我正在研究 .NET 3.5 中的元胞自动机生成器。我决定使用 WPF 是因为我想在 WPF 中学习一些新东西。

我画了一维自动机,如规则 30 和二维自动机,如 Life

我需要一些东西来快速绘制许多图像。

例如,网格尺寸为 64 x 64,单元格尺寸为 12px。所以我一步画出了 64*64 = 4096 张图片。每一步之间的间隔约为100毫秒。

我将我的应用程序重写为 WinForms,一切正常。但是在 WPF 中很慢,我不知道为什么。


我在 WPF 中的绘图示例:

我有一个派生自 Image 的类。在这个类中,我绘制了一个位图,并在 Source 属性中使用它。

        public void DrawAll()
    {

        DrawingGroup dg = new DrawingGroup();


        for (byte i = 0; i < this.DimensionX; ++i)
        {

            for (byte j = 0; j < this.DimensionY; ++j)
            {

                Piece p = this.Mesh[i][j];

                Rect rect = new Rect(j * this.CellSize + (j + 1), i * this.CellSize + (i + 1),
                    this.CellSize, this.CellSize);

                ImageDrawing id = new ImageDrawing();
                id.Rect = rect;

                if (p == null)
                    id.ImageSource = this._undefinedPiece.Image.Source;
                else
                    id.ImageSource = p.Image.Source;


                dg.Children.Add(id);


            }

        }

        DrawingImage di = new DrawingImage(dg);

        this.Source = di;

    }

在 WPF 中绘图的第二个示例:

我从 Canvas 派生类并覆盖 OnRender 函数。基于这篇文章:http://sachabarber.net/?p=675

protected override void OnRender(DrawingContext dc)
    {
        base.OnRender(dc);

        for (byte i = 0; i < this.DimensionX; ++i)
        {

            for (byte j = 0; j < this.DimensionY; ++j)
            {


                Rect rect = new Rect(j * this.CellSize + (j + 1), i * this.CellSize + (i + 1),
                    this.CellSize, this.CellSize);



                BitmapImage bi;

                int counter = i + j + DateTime.Now.Millisecond;

                if (counter % 3 == 0)
                    bi = this.bundefined;
                else if (counter % 3 == 1)
                    bi = this.bwhite;
                else
                    bi = this.bred;


                dc.DrawImage(bi, rect);

                ++counter;

            }

        }
    }

感谢所有回复

【问题讨论】:

    标签: c# .net wpf


    【解决方案1】:

    正如this 文章中所写,在 wpf 中绘制 2D 的最快方法是 StreamGeomerty。 我相信你能够根据这个类的需要调整你的模式生成逻辑。

    【讨论】:

    • 实际上,最后链接的文章使用了InteropBitmap。
    • 我认为在使用不安全代码之前取得的性能已经可以满足大部分需求了。
    • 另一种不使用不安全代码的方法是使用 WriteableBitmap,这当然会比 InteropBitmap 慢一点。
    • 我在看 WriteableBitmap 和 StreamGeometry,但是有可能从 Image 或 ImageSource 绘制图像吗?我没有找到像 DrawImage 之类的东西。
    • 几何图形用于绘制路径。如果您只需要矩形,那就足够了。如果您需要图像 - 我从未尝试过 - 但我认为您可以使用 ImageBrush 绘制填充区域,使用 AlignementX、AlignementY 和 ViewPort 属性使图块与矩形对齐。
    【解决方案2】:

    WPF 真正的力量在于渲染矢量。有没有一种方法可以创建预定大小的矩形对象,而不是使用图像,分配颜色,然后分配位置?位图与 vs 矢量一起使用非常耗费资源。即使 WPF 将渲染推送到显卡,它仍然需要大量处理。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-16
      • 2012-03-29
      相关资源
      最近更新 更多