在 C# 中重用或处理自定义字体的有效方法

Efficient way of reusing or disposing custom fonts in c#

我们有 C# 窗体应用程序,它使用了很多控件和自定义字体,每个控件都有不同的大小。问题在于不断增长的 FONT gdi 对象计数会导致 OutOfMemory 异常(一旦超过 10,000 个计数 - 使用 Bear GDI 测试对此进行了测试)每当重新创建控件时。我试过以下选项,但字体 gdi 不一致:

  1. 重用特定字体 type/size 的每个字体,方法是在静态 class

    中将其声明为静态变量

    静态字体Robo_13Reg_Font=新字体("Roboto",13F,System.Drawing.FontStyle.Regular,System.Drawing.GraphicsUnit.Pixel,((byte)(0)));

  2. 创建一个本地字体变量并在使用完成后释放

  3. 将标签中的字体重新用于所需的控件并处理标签,如下面的代码

 public static void getRobo_13Reg_Font(Control addFontTo)
    {
        try
        {
            if (Robo_13Reg_Font == null)
            {
                Robo_13Reg_Font = new Label();
                Robo_13Reg_Font.Font = new Font("Roboto", 13F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel, ((byte)(0)));
            }
            addFontTo.Font = Robo_13Reg_Font.Font;
            Robo_13Reg_Font.Dispose();
            Robo_13Reg_Font = null;
        }
        finally
        {
        }
    }

感谢您的所有意见!

检查您是否正在创建多个工具提示实例(新工具提示)并在您的应用程序中为工具提示分配字体 - 这也会为正在创建的每个工具提示实例创建字体 GDI 对象,因为我遇到了类似的问题。