WPF画布在绘制大量图形时会冻结

4
我是一名初学者,正在做一些C#练习。我了解到森林火灾模型,并尝试使用WPF进行绘制,我使用画布为每个像素创建矩形。 问题是程序会冻结,画布不会绘制任何东西(在while(true)循环中)。而且,即使在迭代后删除所有子元素,程序仍然会收集GB的内存。
测试简化代码:
public partial class TestDrawing : Window
{
    public TestDrawing()
    {
        InitializeComponent();
    }
    private void btnStart_Click(object sender, RoutedEventArgs e)
    {
        DrawForestFire();
    }
    private void DrawForestFire()
    {

        Random rand = new Random();

        while (true)
        {
            for (int y = 0; y < 100; y++)
            {
                for (int x = 0; x < 100; x++)
                {
                    Rectangle rectangle = new Rectangle();

                    Color color = Color.FromRgb((byte)rand.Next(200), 
                              (byte)rand.Next(200), (byte)rand.Next(200));

                    rectangle.Fill = new SolidColorBrush(color);
                    rectangle.Width = 4;
                    rectangle.Height = 4;

                    Canvas.SetTop(rectangle, y * 4);
                    Canvas.SetLeft(rectangle, x * 4);

                    canvas.Children.Add(rectangle);
                }
            }
            canvas.Children.Clear();
        }
    }
}

我尝试在线程中绘制“DrawForestFire()”,并使用“this.Dispatcher.Invoke(() => { ... });”中的画布对象,但对我来说没有任何区别。出了什么问题?
还有,除了Canvas,是否有更好的方法来执行这种操作?

7
不要在应用程序的 UI 线程中使用 while (true),而是使用计时器,例如 DispatcherTimer。 - Clemens
1
你正在使用一个连续循环来绘制10000个黑色矩形。难怪它变得无响应了。 - Palle Due
而不是绘制10000个矩形,请考虑使用WriteableBitmap。 - Clemens
你看过https://dev59.com/ikrSa4cB1Zd3GeqPTApn吗? - NoRegrets
我尝试使用间隔为2秒的DispatcherTimer,让DrawForestFire()在每个Tick中运行,但它只会冻结一秒钟,什么都没有发生。我想让它在画布上工作,之后我会尝试在位图上运行。 - SergSam
“我想让它在画布中工作” - 你应该至少尝试重用已经存在的矩形。创建它们一次,然后通过迭代Children集合来访问它们。 - Clemens
2个回答

4

不要向画布添加10000个矩形元素,最好在单个WriteableBitmap中绘制。

在XAML中声明一个Image元素。

<Image x:Name="image"/>

将WriteableBitmap分配给其Source属性。然后使用DispatcherTimer更新位图像素:

public partial class MainWindow : Window
{
    private const int width = 100;
    private const int height = 100;

    private readonly Random random = new Random();
    private readonly byte[] buffer = new byte[3 * width * height];
    private readonly WriteableBitmap bitmap =
        new WriteableBitmap(width, height, 96, 96, PixelFormats.Bgr24, null);

    public MainWindow()
    {
        InitializeComponent();

        image.Source = bitmap;

        var timer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(50) };
        timer.Tick += OnTimerTick;
        timer.Start();
    }

    private void UpdateBuffer()
    {
        for (var y = 0; y < height; y++)
        {
            for (var x = 0; x < width; x++)
            {
                var i = 3 * (width * y + x);
                buffer[i++] = (byte)random.Next(200);
                buffer[i++] = (byte)random.Next(200);
                buffer[i++] = (byte)random.Next(200);
            }
        }
    }

    private async void OnTimerTick(object sender, EventArgs e)
    {
        await Task.Run(() => UpdateBuffer());

        bitmap.WritePixels(new Int32Rect(0, 0, width, height), buffer, 3 * width, 0);
    }
}

感谢您的帮助,我使用了位图实现了它,因为我无法通过画布使其工作。不管怎样,我有一个关于您的解决方案的问题,每个像素都不是一个接一个地绘制的,而是在两个循环迭代后全部绘制。在维基百科页面:https://en.wikipedia.org/wiki/Forest-fire_model 中,您可以看到每个像素都是一个接一个地绘制的,我应该在第二个for循环中使用WritePixels吗?如果是这样,具体应该如何操作? - SergSam
模型规则同时应用于网格的所有像素。因此,您应该在每个计时器滴答中为每个像素计算一个新值。将随机颜色替换为代表实际状态的三种颜色之一 - 空白,被树木占据或正在燃烧。 - Clemens

1

仅供娱乐,这是一个可工作的森林火灾实现。我喜欢尝试自燃和新树概率。

public partial class MainWindow : Window
{
    private enum CellState
    {
        Empty, Tree, Burning
    }

    private const int width = 400;
    private const int height = 400;

    private readonly WriteableBitmap bitmap =
        new WriteableBitmap(width, height, 96, 96, PixelFormats.Bgr24, null);

    private readonly byte[] buffer = new byte[3 * width * height];
    private readonly Random random = new Random();

    private readonly Dictionary<CellState, Color> stateColors =
        new Dictionary<CellState, Color>
        {
            { CellState.Empty, Colors.Black },
            { CellState.Tree, Colors.Green },
            { CellState.Burning, Colors.Yellow }
        };

    private CellState[,] cells = new CellState[height, width];

    private double ignitionProbability = 0.0001;
    private double newTreeProbability = 0.01;

    public MainWindow()
    {
        InitializeComponent();

        image.Source = bitmap;

        var timer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(50) };
        timer.Tick += OnTimerTick;
        timer.Start();
    }

    private async void OnTimerTick(object sender, EventArgs e)
    {
        await Task.Run(() => UpdateCells());

        bitmap.WritePixels(new Int32Rect(0, 0, width, height), buffer, 3 * width, 0);
    }

    private bool IsBurning(int y, int x)
    {
        return x >= 0 && x < width && y >= 0 && y < height
            && cells[y, x] == CellState.Burning;
    }

    private bool StartsBurning(int y, int x)
    {
        return IsBurning(y - 1, x - 1)
            || IsBurning(y - 1, x)
            || IsBurning(y - 1, x + 1)
            || IsBurning(y, x - 1)
            || IsBurning(y, x + 1)
            || IsBurning(y + 1, x - 1)
            || IsBurning(y + 1, x)
            || IsBurning(y + 1, x + 1)
            || random.NextDouble() <= ignitionProbability;
    }

    private CellState GetNewState(int y, int x)
    {
        var state = cells[y, x];

        switch (state)
        {
            case CellState.Burning:
                state = CellState.Empty;
                break;

            case CellState.Empty:
                if (random.NextDouble() <= newTreeProbability)
                {
                    state = CellState.Tree;
                }
                break;

            case CellState.Tree:
                if (StartsBurning(y, x))
                {
                    state = CellState.Burning;
                }
                break;
        }

        return state;
    }

    private void UpdateCells()
    {
        var newCells = new CellState[height, width];

        for (var y = 0; y < height; y++)
        {
            for (var x = 0; x < width; x++)
            {
                newCells[y, x] = GetNewState(y, x);

                var color = stateColors[newCells[y, x]];
                var i = 3 * (width * y + x);

                buffer[i++] = color.B;
                buffer[i++] = color.G;
                buffer[i++] = color.R;
            }
        }

        cells = newCells;
    }
}

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