当尝试绘制贴图时OutOfMemoryException

本文关键字:OutOfMemoryException 绘制 | 更新日期: 2023-09-27 18:16:47

我试图在c#中绘制一个tile地图,我所遇到的问题在我看来是奇怪的。

我有一个int数组,用来保存x坐标和y坐标,以便在屏幕上绘制贴图。(两个箭头中有一个是0,另一个是Y)

int[,] level1 = { { 0, 32, 64, 96 }, { 0, 0, 0, 0 } };

以下是我如何使用for循环将部分tile渲染到屏幕上,并且在这里我将在注释掉的一行上获得"OutOfMemoryException":

public void DrawTest(SpriteBatch spriteBatch)
    {
        for (int x = 0;; x++)
        {
            for (int y = 0;; y++)
            {
                x = level1[x, 0];
                y = level1[0, y];
                //This line bellow is where it says OutOfMemoryException
                spriteBatch.Draw(tileSheet, new Rectangle(x, y, 32, 32), new Rectangle(0, 0, 32, 32), Color.White);
                if (x >= 5 | y >= 5)
                {
                    x = 0;
                    y = 0;
                }
            }
        }
    }

当我想调用这个渲染方法时,我在主类中进行渲染方法

levelLoader.DrawTest(this.spriteBatch);

它工作完美之前,我使用这个DrawTest方法来尝试绘制瓷砖。但我完全不知道为什么这不能正常工作。

更新:

public void DrawTest(SpriteBatch spriteBatch)
        {
            for (int x = 0; x < 5 ; x++)
            {
                for (int y = 0; y < 5 ; y++)
                {
                    x = level1[x, 0];
                    y = level1[0, y];
                    spriteBatch.Draw(tileSheet, new Rectangle(x, y, 32, 32), new Rectangle(0, 0, 32, 32), Color.White);
                }
            }
        }

更新2:

        public void DrawTest(SpriteBatch spriteBatch)
    {
        for (int x = 0; x < 5 ; x++)
        {
            for (int y = 0; y < 5 ; y++)
            {
                int tileXCord = level1[x, 0];
                int tileYCord = level1[0, y];
                spriteBatch.Draw(tileSheet, new Rectangle(tileXCord, tileYCord, 32, 32), new Rectangle(0, 0, 32, 32), Color.White);
            }
        }
    }

当尝试绘制贴图时OutOfMemoryException

我看到你的代码中有几个问题:

  1. 你有一个无限循环在你的代码。嵌套循环的终止条件是什么?
  2. (重要!)spriteBatch.Draw()方法并不绘制任何内容,它只是安排精灵的绘制。该方法调用之前应该先调用spriteBatch.Begin()(开始调度绘图),最后必须调用spriteBatch.End()将调度的站点刷新到设备上。你的无限循环导致你的精灵绘图的无限调度,直到内存满,你面临内存不足的异常。
  3. (请注意!)在您的(x >= 5 | y >= 5)条件下,您正在使用位或比较,您不应该这样做(除非是故意的,我在这里没有看到,而是使用布尔或:(x >= 5 || y >= 5)
  4. 在循环本身中修改循环计数器是一个非常坏的习惯。它不仅容易出错,而且很难理解和支持这样编写的代码。

我会这样重写你的代码

    spriteBatch.Begin();
    for (int x = 0; x < 5; x++)
    {
        for (int y = 0; y < 5; y++)
        {
            x = level1[x, 0];
            y = level1[0, y];
            //This line bellow is where it says OutOfMemoryException
            spriteBatch.Draw(tileSheet, new Rectangle(x, y, 32, 32), new Rectangle(0, 0, 32, 32), Color.White);
        }
    }
    spriteBatch.End();

它将在主游戏循环的每个Draw()事件上重新绘制所有的瓷砖(前提是你仍然从你的Game类的Draw()方法调用这个方法)。XNA会根据PC的性能和每帧的计算量来改变FPS速率。

我认为你陷入了无限循环。您需要退出以避免内存不足异常。

相关文章:
  • 没有找到相关文章