需要在WPF中快速绘制多张图片的工具

6
我正在开发.NET 3.5中的元胞自动机生成器。我决定使用WPF,因为我想学习一些新的WPF知识。
我绘制像Rule 30这样的一维元胞自动机和生命游戏这样的二维元胞自动机。
我需要一种快速绘制多张图片的方法。
例如,网格的尺寸为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;

            }

        }
    }

感谢所有回复。
3个回答

3

此文所述,wpf中绘制2D图形的最快方法是使用StreamGeomerty类。我相信你能够将你的模式生成逻辑适应这个类的需求。


实际上,末尾链接的文章使用了InteropBitmap。 - Jens
我认为在使用不安全代码之前实现的性能已经适合大多数需求。 - BertuPG
一种不需要使用不安全代码的替代方法是使用WriteableBitmap,当然这会比InteropBitmap慢一些。 - BertuPG
我正在研究WriteableBitmap和StreamGeometry,但是有没有可能从Image或ImageSource绘制图像?我没有找到类似于DrawImage等的东西。 - austinem
几何图形用于绘制路径。如果你只需要矩形,那就足够了。如果你需要图片——我从未尝试过——但我认为你可以使用ImageBrush来填充区域,使用AlignementX、AlignementY和ViewPort属性来使瓷砖与你的矩形对齐。 - BertuPG

1

WPF的真正强大之处在于渲染矢量图形。有没有一种方法,可以创建预定大小的矩形对象,分配颜色,然后分配位置,而不是使用图像?与矢量图相比,位图的资源消耗相当大。即使WPF将渲染推送到视频卡上,仍然需要进行大量处理。


0
你可以创建一个“图标字体”,其中包含你的图片,而不是典型的字符。通过字体显示图像与将其用于常规文本没有区别。
<TextBlock Text="&#xE726" FontFamily="Segoe MDL2 Assets" Foreground="Red"/>

enter image description here

优点:

  • 字形可以无损缩放
  • 可以设置不同的颜色
  • 形状/路径具有更好的性能

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接