c# - 如何避免在 openTK 中使用动态文本耗尽内存

标签 c# opengl memory visual-studio-2013 opentk

我一直在尝试在 openTK(在 c# 中)的屏幕上绘制一个计时器,为此我一直在生成新纹理并删除旧纹理,但我的程序仍然占用内存直到崩溃,因为没有足够的空间用于另一个位图。

这是我正在做的:

        text_bmp = new Bitmap(width, height);
        text_bmp_gfx = Graphics.FromImage(text_bmp);
        text_bmp_gfx.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;
        text_bmp_gfx.Clear(Color.Transparent);
        text_bmp_gfx.DrawString(music.getCurrentTime(), new Font("Exo 2", 12), drawBrush, new PointF(0.0F, 0.0F));
        text_bmp_gfx.DrawString(timer.Elapsed.ToString(), new Font("Exo 2", 12), drawBrush, new PointF(0.0F, 18.0F));
        GL.DeleteTexture(TextTexture);
        TextTexture = ContentPipe.LoadTextureFromBitmap(text_bmp);
        GL.BindTexture(TextureTarget.Texture2D, TextTexture);

其中 content pipe.loadtexturefrombitmap 是这个函数:

public static int LoadTextureFromBitmap(Bitmap bmp)
    {
        int id = GL.GenTexture();
        GL.BindTexture(TextureTarget.Texture2D, id);
        BitmapData data = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
        GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, data.Width, data.Height, 0, OpenTK.Graphics.OpenGL.PixelFormat.Bgra, PixelType.UnsignedByte, data.Scan0);
        bmp.UnlockBits(data);
        GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)TextureWrapMode.Clamp);
        GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)TextureWrapMode.Clamp);
        GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear);
        GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear);
        bmp = null;
        return id;
    }

老实说,第二部分是从 youtube 教程中复制的,所以我不确定它是如何工作的。

我认为问题是在我不需要 openTK 纹理后,我没有正确地从它们中释放内存,所以我生成了大量图像,但我不知道如何解决这个问题。

最佳答案

对于那些发现这一点的人来说,有两个重要的部分:

在位图和图形对象上调用 dispose()

手动垃圾收集。

每秒制作 60 张大图像对于自动垃圾收集来说显然有点多,所以我每帧调用一次垃圾收集,效果很好!

关于c# - 如何避免在 openTK 中使用动态文本耗尽内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31096495/

相关文章:

C# MYSQL - 我无法插入 bool 值

c# - Simple Injector在BaseClass中注入(inject)多个依赖项

c - 使用 VBO 绘制 .obj

c++ - CMake:使用 target_compile_options 设置 ggc-min-expand 和 -heapsize

c - 为什么 malloc 使用零大小?

c# - 在 Razor View 中遍历列表

c# - return View(model) 和 return RedirectToAction ("ViewName",model) 有什么区别

opengl - VBO 如何连接到 VAO

java - 浏览器渲染和流式传输

拍照时 iOS 应用程序崩溃